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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
8,200
quiltdata/quilt
compiler/quilt/tools/store.py
PackageStore.prune
def prune(self, objs=None): """ Clean up objects not referenced by any packages. Try to prune all objects by default. """ if objs is None: objdir = os.path.join(self._path, self.OBJ_DIR) objs = os.listdir(objdir) remove_objs = set(objs) for pkg in self.iterpackages(): remove_objs.difference_update(find_object_hashes(pkg)) for obj in remove_objs: path = self.object_path(obj) if os.path.exists(path): os.chmod(path, S_IWUSR) os.remove(path) return remove_objs
python
def prune(self, objs=None): """ Clean up objects not referenced by any packages. Try to prune all objects by default. """ if objs is None: objdir = os.path.join(self._path, self.OBJ_DIR) objs = os.listdir(objdir) remove_objs = set(objs) for pkg in self.iterpackages(): remove_objs.difference_update(find_object_hashes(pkg)) for obj in remove_objs: path = self.object_path(obj) if os.path.exists(path): os.chmod(path, S_IWUSR) os.remove(path) return remove_objs
[ "def", "prune", "(", "self", ",", "objs", "=", "None", ")", ":", "if", "objs", "is", "None", ":", "objdir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "self", ".", "OBJ_DIR", ")", "objs", "=", "os", ".", "listdir", "(", "objdir", ")", "remove_objs", "=", "set", "(", "objs", ")", "for", "pkg", "in", "self", ".", "iterpackages", "(", ")", ":", "remove_objs", ".", "difference_update", "(", "find_object_hashes", "(", "pkg", ")", ")", "for", "obj", "in", "remove_objs", ":", "path", "=", "self", ".", "object_path", "(", "obj", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "chmod", "(", "path", ",", "S_IWUSR", ")", "os", ".", "remove", "(", "path", ")", "return", "remove_objs" ]
Clean up objects not referenced by any packages. Try to prune all objects by default.
[ "Clean", "up", "objects", "not", "referenced", "by", "any", "packages", ".", "Try", "to", "prune", "all", "objects", "by", "default", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L365-L383
8,201
quiltdata/quilt
compiler/quilt/tools/store.py
PackageStore.save_dataframe
def save_dataframe(self, dataframe): """ Save a DataFrame to the store. """ storepath = self.temporary_object_path(str(uuid.uuid4())) # switch parquet lib parqlib = self.get_parquet_lib() if isinstance(dataframe, pd.DataFrame): #parqlib is ParquetLib.ARROW: # other parquet libs are deprecated, remove? import pyarrow as pa from pyarrow import parquet table = pa.Table.from_pandas(dataframe) parquet.write_table(table, storepath) elif parqlib is ParquetLib.SPARK: from pyspark import sql as sparksql assert isinstance(dataframe, sparksql.DataFrame) dataframe.write.parquet(storepath) else: assert False, "Unimplemented ParquetLib %s" % parqlib # Move serialized DataFrame to object store if os.path.isdir(storepath): # Pyspark hashes = [] files = [ofile for ofile in os.listdir(storepath) if ofile.endswith(".parquet")] for obj in files: path = os.path.join(storepath, obj) objhash = digest_file(path) self._move_to_store(path, objhash) hashes.append(objhash) rmtree(storepath) else: filehash = digest_file(storepath) self._move_to_store(storepath, filehash) hashes = [filehash] return hashes
python
def save_dataframe(self, dataframe): """ Save a DataFrame to the store. """ storepath = self.temporary_object_path(str(uuid.uuid4())) # switch parquet lib parqlib = self.get_parquet_lib() if isinstance(dataframe, pd.DataFrame): #parqlib is ParquetLib.ARROW: # other parquet libs are deprecated, remove? import pyarrow as pa from pyarrow import parquet table = pa.Table.from_pandas(dataframe) parquet.write_table(table, storepath) elif parqlib is ParquetLib.SPARK: from pyspark import sql as sparksql assert isinstance(dataframe, sparksql.DataFrame) dataframe.write.parquet(storepath) else: assert False, "Unimplemented ParquetLib %s" % parqlib # Move serialized DataFrame to object store if os.path.isdir(storepath): # Pyspark hashes = [] files = [ofile for ofile in os.listdir(storepath) if ofile.endswith(".parquet")] for obj in files: path = os.path.join(storepath, obj) objhash = digest_file(path) self._move_to_store(path, objhash) hashes.append(objhash) rmtree(storepath) else: filehash = digest_file(storepath) self._move_to_store(storepath, filehash) hashes = [filehash] return hashes
[ "def", "save_dataframe", "(", "self", ",", "dataframe", ")", ":", "storepath", "=", "self", ".", "temporary_object_path", "(", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ")", "# switch parquet lib", "parqlib", "=", "self", ".", "get_parquet_lib", "(", ")", "if", "isinstance", "(", "dataframe", ",", "pd", ".", "DataFrame", ")", ":", "#parqlib is ParquetLib.ARROW: # other parquet libs are deprecated, remove?", "import", "pyarrow", "as", "pa", "from", "pyarrow", "import", "parquet", "table", "=", "pa", ".", "Table", ".", "from_pandas", "(", "dataframe", ")", "parquet", ".", "write_table", "(", "table", ",", "storepath", ")", "elif", "parqlib", "is", "ParquetLib", ".", "SPARK", ":", "from", "pyspark", "import", "sql", "as", "sparksql", "assert", "isinstance", "(", "dataframe", ",", "sparksql", ".", "DataFrame", ")", "dataframe", ".", "write", ".", "parquet", "(", "storepath", ")", "else", ":", "assert", "False", ",", "\"Unimplemented ParquetLib %s\"", "%", "parqlib", "# Move serialized DataFrame to object store", "if", "os", ".", "path", ".", "isdir", "(", "storepath", ")", ":", "# Pyspark", "hashes", "=", "[", "]", "files", "=", "[", "ofile", "for", "ofile", "in", "os", ".", "listdir", "(", "storepath", ")", "if", "ofile", ".", "endswith", "(", "\".parquet\"", ")", "]", "for", "obj", "in", "files", ":", "path", "=", "os", ".", "path", ".", "join", "(", "storepath", ",", "obj", ")", "objhash", "=", "digest_file", "(", "path", ")", "self", ".", "_move_to_store", "(", "path", ",", "objhash", ")", "hashes", ".", "append", "(", "objhash", ")", "rmtree", "(", "storepath", ")", "else", ":", "filehash", "=", "digest_file", "(", "storepath", ")", "self", ".", "_move_to_store", "(", "storepath", ",", "filehash", ")", "hashes", "=", "[", "filehash", "]", "return", "hashes" ]
Save a DataFrame to the store.
[ "Save", "a", "DataFrame", "to", "the", "store", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L436-L472
8,202
quiltdata/quilt
compiler/quilt/tools/store.py
PackageStore.load_numpy
def load_numpy(self, hash_list): """ Loads a numpy array. """ assert len(hash_list) == 1 self._check_hashes(hash_list) with open(self.object_path(hash_list[0]), 'rb') as fd: return np.load(fd, allow_pickle=False)
python
def load_numpy(self, hash_list): """ Loads a numpy array. """ assert len(hash_list) == 1 self._check_hashes(hash_list) with open(self.object_path(hash_list[0]), 'rb') as fd: return np.load(fd, allow_pickle=False)
[ "def", "load_numpy", "(", "self", ",", "hash_list", ")", ":", "assert", "len", "(", "hash_list", ")", "==", "1", "self", ".", "_check_hashes", "(", "hash_list", ")", "with", "open", "(", "self", ".", "object_path", "(", "hash_list", "[", "0", "]", ")", ",", "'rb'", ")", "as", "fd", ":", "return", "np", ".", "load", "(", "fd", ",", "allow_pickle", "=", "False", ")" ]
Loads a numpy array.
[ "Loads", "a", "numpy", "array", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L474-L481
8,203
quiltdata/quilt
compiler/quilt/tools/store.py
PackageStore.get_file
def get_file(self, hash_list): """ Returns the path of the file - but verifies that the hash is actually present. """ assert len(hash_list) == 1 self._check_hashes(hash_list) return self.object_path(hash_list[0])
python
def get_file(self, hash_list): """ Returns the path of the file - but verifies that the hash is actually present. """ assert len(hash_list) == 1 self._check_hashes(hash_list) return self.object_path(hash_list[0])
[ "def", "get_file", "(", "self", ",", "hash_list", ")", ":", "assert", "len", "(", "hash_list", ")", "==", "1", "self", ".", "_check_hashes", "(", "hash_list", ")", "return", "self", ".", "object_path", "(", "hash_list", "[", "0", "]", ")" ]
Returns the path of the file - but verifies that the hash is actually present.
[ "Returns", "the", "path", "of", "the", "file", "-", "but", "verifies", "that", "the", "hash", "is", "actually", "present", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L493-L499
8,204
quiltdata/quilt
compiler/quilt/tools/store.py
PackageStore.save_metadata
def save_metadata(self, metadata): """ Save metadata to the store. """ if metadata in (None, {}): return None if SYSTEM_METADATA in metadata: raise StoreException("Not allowed to store %r in metadata" % SYSTEM_METADATA) path = self.temporary_object_path(str(uuid.uuid4())) with open(path, 'w') as fd: try: # IMPORTANT: JSON format affects the hash of the package. # In particular, it cannot contain line breaks because of Windows (LF vs CRLF). # To be safe, we use the most compact encoding. json.dump(metadata, fd, sort_keys=True, separators=(',', ':')) except (TypeError, ValueError): raise StoreException("Metadata is not serializable") metahash = digest_file(path) self._move_to_store(path, metahash) return metahash
python
def save_metadata(self, metadata): """ Save metadata to the store. """ if metadata in (None, {}): return None if SYSTEM_METADATA in metadata: raise StoreException("Not allowed to store %r in metadata" % SYSTEM_METADATA) path = self.temporary_object_path(str(uuid.uuid4())) with open(path, 'w') as fd: try: # IMPORTANT: JSON format affects the hash of the package. # In particular, it cannot contain line breaks because of Windows (LF vs CRLF). # To be safe, we use the most compact encoding. json.dump(metadata, fd, sort_keys=True, separators=(',', ':')) except (TypeError, ValueError): raise StoreException("Metadata is not serializable") metahash = digest_file(path) self._move_to_store(path, metahash) return metahash
[ "def", "save_metadata", "(", "self", ",", "metadata", ")", ":", "if", "metadata", "in", "(", "None", ",", "{", "}", ")", ":", "return", "None", "if", "SYSTEM_METADATA", "in", "metadata", ":", "raise", "StoreException", "(", "\"Not allowed to store %r in metadata\"", "%", "SYSTEM_METADATA", ")", "path", "=", "self", ".", "temporary_object_path", "(", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "fd", ":", "try", ":", "# IMPORTANT: JSON format affects the hash of the package.", "# In particular, it cannot contain line breaks because of Windows (LF vs CRLF).", "# To be safe, we use the most compact encoding.", "json", ".", "dump", "(", "metadata", ",", "fd", ",", "sort_keys", "=", "True", ",", "separators", "=", "(", "','", ",", "':'", ")", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "StoreException", "(", "\"Metadata is not serializable\"", ")", "metahash", "=", "digest_file", "(", "path", ")", "self", ".", "_move_to_store", "(", "path", ",", "metahash", ")", "return", "metahash" ]
Save metadata to the store.
[ "Save", "metadata", "to", "the", "store", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L521-L544
8,205
quiltdata/quilt
compiler/quilt/tools/store.py
PackageStore.save_package_contents
def save_package_contents(self, root, team, owner, pkgname): """ Saves the in-memory contents to a file in the local package repository. """ assert isinstance(root, RootNode) instance_hash = hash_contents(root) pkg_path = self.package_path(team, owner, pkgname) if not os.path.isdir(pkg_path): os.makedirs(pkg_path) os.mkdir(os.path.join(pkg_path, self.CONTENTS_DIR)) os.mkdir(os.path.join(pkg_path, self.TAGS_DIR)) os.mkdir(os.path.join(pkg_path, self.VERSIONS_DIR)) dest = os.path.join(pkg_path, self.CONTENTS_DIR, instance_hash) with open(dest, 'w') as contents_file: json.dump(root, contents_file, default=encode_node, indent=2, sort_keys=True) tag_dir = os.path.join(pkg_path, self.TAGS_DIR) if not os.path.isdir(tag_dir): os.mkdir(tag_dir) latest_tag = os.path.join(pkg_path, self.TAGS_DIR, self.LATEST) with open (latest_tag, 'w') as tagfile: tagfile.write("{hsh}".format(hsh=instance_hash))
python
def save_package_contents(self, root, team, owner, pkgname): """ Saves the in-memory contents to a file in the local package repository. """ assert isinstance(root, RootNode) instance_hash = hash_contents(root) pkg_path = self.package_path(team, owner, pkgname) if not os.path.isdir(pkg_path): os.makedirs(pkg_path) os.mkdir(os.path.join(pkg_path, self.CONTENTS_DIR)) os.mkdir(os.path.join(pkg_path, self.TAGS_DIR)) os.mkdir(os.path.join(pkg_path, self.VERSIONS_DIR)) dest = os.path.join(pkg_path, self.CONTENTS_DIR, instance_hash) with open(dest, 'w') as contents_file: json.dump(root, contents_file, default=encode_node, indent=2, sort_keys=True) tag_dir = os.path.join(pkg_path, self.TAGS_DIR) if not os.path.isdir(tag_dir): os.mkdir(tag_dir) latest_tag = os.path.join(pkg_path, self.TAGS_DIR, self.LATEST) with open (latest_tag, 'w') as tagfile: tagfile.write("{hsh}".format(hsh=instance_hash))
[ "def", "save_package_contents", "(", "self", ",", "root", ",", "team", ",", "owner", ",", "pkgname", ")", ":", "assert", "isinstance", "(", "root", ",", "RootNode", ")", "instance_hash", "=", "hash_contents", "(", "root", ")", "pkg_path", "=", "self", ".", "package_path", "(", "team", ",", "owner", ",", "pkgname", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "pkg_path", ")", ":", "os", ".", "makedirs", "(", "pkg_path", ")", "os", ".", "mkdir", "(", "os", ".", "path", ".", "join", "(", "pkg_path", ",", "self", ".", "CONTENTS_DIR", ")", ")", "os", ".", "mkdir", "(", "os", ".", "path", ".", "join", "(", "pkg_path", ",", "self", ".", "TAGS_DIR", ")", ")", "os", ".", "mkdir", "(", "os", ".", "path", ".", "join", "(", "pkg_path", ",", "self", ".", "VERSIONS_DIR", ")", ")", "dest", "=", "os", ".", "path", ".", "join", "(", "pkg_path", ",", "self", ".", "CONTENTS_DIR", ",", "instance_hash", ")", "with", "open", "(", "dest", ",", "'w'", ")", "as", "contents_file", ":", "json", ".", "dump", "(", "root", ",", "contents_file", ",", "default", "=", "encode_node", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ")", "tag_dir", "=", "os", ".", "path", ".", "join", "(", "pkg_path", ",", "self", ".", "TAGS_DIR", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "tag_dir", ")", ":", "os", ".", "mkdir", "(", "tag_dir", ")", "latest_tag", "=", "os", ".", "path", ".", "join", "(", "pkg_path", ",", "self", ".", "TAGS_DIR", ",", "self", ".", "LATEST", ")", "with", "open", "(", "latest_tag", ",", "'w'", ")", "as", "tagfile", ":", "tagfile", ".", "write", "(", "\"{hsh}\"", ".", "format", "(", "hsh", "=", "instance_hash", ")", ")" ]
Saves the in-memory contents to a file in the local package repository.
[ "Saves", "the", "in", "-", "memory", "contents", "to", "a", "file", "in", "the", "local", "package", "repository", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L546-L570
8,206
quiltdata/quilt
compiler/quilt/tools/store.py
PackageStore._move_to_store
def _move_to_store(self, srcpath, objhash): """ Make the object read-only and move it to the store. """ destpath = self.object_path(objhash) if os.path.exists(destpath): # Windows: delete any existing object at the destination. os.chmod(destpath, S_IWUSR) os.remove(destpath) os.chmod(srcpath, S_IRUSR | S_IRGRP | S_IROTH) # Make read-only move(srcpath, destpath)
python
def _move_to_store(self, srcpath, objhash): """ Make the object read-only and move it to the store. """ destpath = self.object_path(objhash) if os.path.exists(destpath): # Windows: delete any existing object at the destination. os.chmod(destpath, S_IWUSR) os.remove(destpath) os.chmod(srcpath, S_IRUSR | S_IRGRP | S_IROTH) # Make read-only move(srcpath, destpath)
[ "def", "_move_to_store", "(", "self", ",", "srcpath", ",", "objhash", ")", ":", "destpath", "=", "self", ".", "object_path", "(", "objhash", ")", "if", "os", ".", "path", ".", "exists", "(", "destpath", ")", ":", "# Windows: delete any existing object at the destination.", "os", ".", "chmod", "(", "destpath", ",", "S_IWUSR", ")", "os", ".", "remove", "(", "destpath", ")", "os", ".", "chmod", "(", "srcpath", ",", "S_IRUSR", "|", "S_IRGRP", "|", "S_IROTH", ")", "# Make read-only", "move", "(", "srcpath", ",", "destpath", ")" ]
Make the object read-only and move it to the store.
[ "Make", "the", "object", "read", "-", "only", "and", "move", "it", "to", "the", "store", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L572-L582
8,207
quiltdata/quilt
compiler/quilt/tools/store.py
PackageStore.add_to_package_numpy
def add_to_package_numpy(self, root, ndarray, node_path, target, source_path, transform, custom_meta): """ Save a Numpy array to the store. """ filehash = self.save_numpy(ndarray) metahash = self.save_metadata(custom_meta) self._add_to_package_contents(root, node_path, [filehash], target, source_path, transform, metahash)
python
def add_to_package_numpy(self, root, ndarray, node_path, target, source_path, transform, custom_meta): """ Save a Numpy array to the store. """ filehash = self.save_numpy(ndarray) metahash = self.save_metadata(custom_meta) self._add_to_package_contents(root, node_path, [filehash], target, source_path, transform, metahash)
[ "def", "add_to_package_numpy", "(", "self", ",", "root", ",", "ndarray", ",", "node_path", ",", "target", ",", "source_path", ",", "transform", ",", "custom_meta", ")", ":", "filehash", "=", "self", ".", "save_numpy", "(", "ndarray", ")", "metahash", "=", "self", ".", "save_metadata", "(", "custom_meta", ")", "self", ".", "_add_to_package_contents", "(", "root", ",", "node_path", ",", "[", "filehash", "]", ",", "target", ",", "source_path", ",", "transform", ",", "metahash", ")" ]
Save a Numpy array to the store.
[ "Save", "a", "Numpy", "array", "to", "the", "store", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L638-L644
8,208
quiltdata/quilt
compiler/quilt/tools/store.py
PackageStore.add_to_package_package_tree
def add_to_package_package_tree(self, root, node_path, pkgnode): """ Adds a package or sub-package tree from an existing package to this package's contents. """ if node_path: ptr = root for node in node_path[:-1]: ptr = ptr.children.setdefault(node, GroupNode(dict())) ptr.children[node_path[-1]] = pkgnode else: if root.children: raise PackageException("Attempting to overwrite root node of a non-empty package.") root.children = pkgnode.children.copy()
python
def add_to_package_package_tree(self, root, node_path, pkgnode): """ Adds a package or sub-package tree from an existing package to this package's contents. """ if node_path: ptr = root for node in node_path[:-1]: ptr = ptr.children.setdefault(node, GroupNode(dict())) ptr.children[node_path[-1]] = pkgnode else: if root.children: raise PackageException("Attempting to overwrite root node of a non-empty package.") root.children = pkgnode.children.copy()
[ "def", "add_to_package_package_tree", "(", "self", ",", "root", ",", "node_path", ",", "pkgnode", ")", ":", "if", "node_path", ":", "ptr", "=", "root", "for", "node", "in", "node_path", "[", ":", "-", "1", "]", ":", "ptr", "=", "ptr", ".", "children", ".", "setdefault", "(", "node", ",", "GroupNode", "(", "dict", "(", ")", ")", ")", "ptr", ".", "children", "[", "node_path", "[", "-", "1", "]", "]", "=", "pkgnode", "else", ":", "if", "root", ".", "children", ":", "raise", "PackageException", "(", "\"Attempting to overwrite root node of a non-empty package.\"", ")", "root", ".", "children", "=", "pkgnode", ".", "children", ".", "copy", "(", ")" ]
Adds a package or sub-package tree from an existing package to this package's contents.
[ "Adds", "a", "package", "or", "sub", "-", "package", "tree", "from", "an", "existing", "package", "to", "this", "package", "s", "contents", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L658-L671
8,209
quiltdata/quilt
compiler/quilt/__init__.py
_install_interrupt_handler
def _install_interrupt_handler(): """Suppress KeyboardInterrupt traceback display in specific situations If not running in dev mode, and if executed from the command line, then we raise SystemExit instead of KeyboardInterrupt. This provides a clean exit. :returns: None if no action is taken, original interrupt handler otherwise """ # These would clutter the quilt.x namespace, so they're imported here instead. import os import sys import signal import pkg_resources from .tools import const # Check to see what entry points / scripts are configred to run quilt from the CLI # By doing this, we have these benefits: # * Avoid closing someone's Jupyter/iPython/bPython session when they hit ctrl-c # * Avoid calling exit() when being used as an external lib # * Provide exceptions when running in Jupyter/iPython/bPython # * Provide exceptions when running in unexpected circumstances quilt = pkg_resources.get_distribution('quilt') executable = os.path.basename(sys.argv[0]) entry_points = quilt.get_entry_map().get('console_scripts', []) # When python is run with '-c', this was executed via 'python -c "<some python code>"' if executable == '-c': # This is awkward and somewhat hackish, but we have to ensure that this is *us* # executing via 'python -c' if len(sys.argv) > 1 and sys.argv[1] == 'quilt testing': # it's us. Let's pretend '-c' is an entry point. entry_points['-c'] = 'blah' sys.argv.pop(1) if executable not in entry_points: return # We're running as a console script. # If not in dev mode, use SystemExit instead of raising KeyboardInterrupt def handle_interrupt(signum, stack): # Check for dev mode if _DEV_MODE is None: # Args and environment have not been parsed, and no _DEV_MODE state has been set. dev_mode = True if len(sys.argv) > 1 and sys.argv[1] == '--dev' else False dev_mode = True if os.environ.get('QUILT_DEV_MODE', '').strip().lower() == 'true' else dev_mode else: # Use forced dev-mode if _DEV_MODE is set dev_mode = _DEV_MODE # In order to display the full traceback, we lose control of the exit code here. # Dev mode ctrl-c exit just produces the generic exit error code 1 if dev_mode: raise KeyboardInterrupt() # Normal exit # avoid annoying prompt displacement when hitting ctrl-c print() exit(const.EXIT_KB_INTERRUPT) return signal.signal(signal.SIGINT, handle_interrupt)
python
def _install_interrupt_handler(): """Suppress KeyboardInterrupt traceback display in specific situations If not running in dev mode, and if executed from the command line, then we raise SystemExit instead of KeyboardInterrupt. This provides a clean exit. :returns: None if no action is taken, original interrupt handler otherwise """ # These would clutter the quilt.x namespace, so they're imported here instead. import os import sys import signal import pkg_resources from .tools import const # Check to see what entry points / scripts are configred to run quilt from the CLI # By doing this, we have these benefits: # * Avoid closing someone's Jupyter/iPython/bPython session when they hit ctrl-c # * Avoid calling exit() when being used as an external lib # * Provide exceptions when running in Jupyter/iPython/bPython # * Provide exceptions when running in unexpected circumstances quilt = pkg_resources.get_distribution('quilt') executable = os.path.basename(sys.argv[0]) entry_points = quilt.get_entry_map().get('console_scripts', []) # When python is run with '-c', this was executed via 'python -c "<some python code>"' if executable == '-c': # This is awkward and somewhat hackish, but we have to ensure that this is *us* # executing via 'python -c' if len(sys.argv) > 1 and sys.argv[1] == 'quilt testing': # it's us. Let's pretend '-c' is an entry point. entry_points['-c'] = 'blah' sys.argv.pop(1) if executable not in entry_points: return # We're running as a console script. # If not in dev mode, use SystemExit instead of raising KeyboardInterrupt def handle_interrupt(signum, stack): # Check for dev mode if _DEV_MODE is None: # Args and environment have not been parsed, and no _DEV_MODE state has been set. dev_mode = True if len(sys.argv) > 1 and sys.argv[1] == '--dev' else False dev_mode = True if os.environ.get('QUILT_DEV_MODE', '').strip().lower() == 'true' else dev_mode else: # Use forced dev-mode if _DEV_MODE is set dev_mode = _DEV_MODE # In order to display the full traceback, we lose control of the exit code here. # Dev mode ctrl-c exit just produces the generic exit error code 1 if dev_mode: raise KeyboardInterrupt() # Normal exit # avoid annoying prompt displacement when hitting ctrl-c print() exit(const.EXIT_KB_INTERRUPT) return signal.signal(signal.SIGINT, handle_interrupt)
[ "def", "_install_interrupt_handler", "(", ")", ":", "# These would clutter the quilt.x namespace, so they're imported here instead.", "import", "os", "import", "sys", "import", "signal", "import", "pkg_resources", "from", ".", "tools", "import", "const", "# Check to see what entry points / scripts are configred to run quilt from the CLI", "# By doing this, we have these benefits:", "# * Avoid closing someone's Jupyter/iPython/bPython session when they hit ctrl-c", "# * Avoid calling exit() when being used as an external lib", "# * Provide exceptions when running in Jupyter/iPython/bPython", "# * Provide exceptions when running in unexpected circumstances", "quilt", "=", "pkg_resources", ".", "get_distribution", "(", "'quilt'", ")", "executable", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", "entry_points", "=", "quilt", ".", "get_entry_map", "(", ")", ".", "get", "(", "'console_scripts'", ",", "[", "]", ")", "# When python is run with '-c', this was executed via 'python -c \"<some python code>\"'", "if", "executable", "==", "'-c'", ":", "# This is awkward and somewhat hackish, but we have to ensure that this is *us*", "# executing via 'python -c'", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", "and", "sys", ".", "argv", "[", "1", "]", "==", "'quilt testing'", ":", "# it's us. Let's pretend '-c' is an entry point.", "entry_points", "[", "'-c'", "]", "=", "'blah'", "sys", ".", "argv", ".", "pop", "(", "1", ")", "if", "executable", "not", "in", "entry_points", ":", "return", "# We're running as a console script.", "# If not in dev mode, use SystemExit instead of raising KeyboardInterrupt", "def", "handle_interrupt", "(", "signum", ",", "stack", ")", ":", "# Check for dev mode", "if", "_DEV_MODE", "is", "None", ":", "# Args and environment have not been parsed, and no _DEV_MODE state has been set.", "dev_mode", "=", "True", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", "and", "sys", ".", "argv", "[", "1", "]", "==", "'--dev'", "else", "False", "dev_mode", "=", "True", "if", "os", ".", "environ", ".", "get", "(", "'QUILT_DEV_MODE'", ",", "''", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "==", "'true'", "else", "dev_mode", "else", ":", "# Use forced dev-mode if _DEV_MODE is set", "dev_mode", "=", "_DEV_MODE", "# In order to display the full traceback, we lose control of the exit code here.", "# Dev mode ctrl-c exit just produces the generic exit error code 1", "if", "dev_mode", ":", "raise", "KeyboardInterrupt", "(", ")", "# Normal exit", "# avoid annoying prompt displacement when hitting ctrl-c", "print", "(", ")", "exit", "(", "const", ".", "EXIT_KB_INTERRUPT", ")", "return", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "handle_interrupt", ")" ]
Suppress KeyboardInterrupt traceback display in specific situations If not running in dev mode, and if executed from the command line, then we raise SystemExit instead of KeyboardInterrupt. This provides a clean exit. :returns: None if no action is taken, original interrupt handler otherwise
[ "Suppress", "KeyboardInterrupt", "traceback", "display", "in", "specific", "situations" ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/__init__.py#L23-L80
8,210
quiltdata/quilt
compiler/quilt/nodes.py
GroupNode._data_keys
def _data_keys(self): """ every child key referencing a dataframe """ return [name for name, child in iteritems(self._children) if not isinstance(child, GroupNode)]
python
def _data_keys(self): """ every child key referencing a dataframe """ return [name for name, child in iteritems(self._children) if not isinstance(child, GroupNode)]
[ "def", "_data_keys", "(", "self", ")", ":", "return", "[", "name", "for", "name", ",", "child", "in", "iteritems", "(", "self", ".", "_children", ")", "if", "not", "isinstance", "(", "child", ",", "GroupNode", ")", "]" ]
every child key referencing a dataframe
[ "every", "child", "key", "referencing", "a", "dataframe" ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/nodes.py#L162-L166
8,211
quiltdata/quilt
compiler/quilt/nodes.py
GroupNode._group_keys
def _group_keys(self): """ every child key referencing a group that is not a dataframe """ return [name for name, child in iteritems(self._children) if isinstance(child, GroupNode)]
python
def _group_keys(self): """ every child key referencing a group that is not a dataframe """ return [name for name, child in iteritems(self._children) if isinstance(child, GroupNode)]
[ "def", "_group_keys", "(", "self", ")", ":", "return", "[", "name", "for", "name", ",", "child", "in", "iteritems", "(", "self", ".", "_children", ")", "if", "isinstance", "(", "child", ",", "GroupNode", ")", "]" ]
every child key referencing a group that is not a dataframe
[ "every", "child", "key", "referencing", "a", "group", "that", "is", "not", "a", "dataframe" ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/nodes.py#L168-L172
8,212
quiltdata/quilt
compiler/quilt/nodes.py
GroupNode._data
def _data(self, asa=None): """ Merges all child dataframes. Only works for dataframes stored on disk - not in memory. """ hash_list = [] stack = [self] alldfs = True store = None while stack: node = stack.pop() if isinstance(node, GroupNode): stack.extend(child for _, child in sorted(node._items(), reverse=True)) else: if node._target() != TargetType.PANDAS: alldfs = False if node._store is None or node._hashes is None: msg = "Can only merge built dataframes. Build this package and try again." raise NotImplementedError(msg) node_store = node._store if store is None: store = node_store if node_store != store: raise NotImplementedError("Can only merge dataframes from the same store") hash_list += node._hashes if asa is None: if not hash_list: return None if not alldfs: raise ValueError("Group contains non-dataframe nodes") return store.load_dataframe(hash_list) else: if hash_list: assert store is not None return asa(self, [store.object_path(obj) for obj in hash_list]) else: return asa(self, [])
python
def _data(self, asa=None): """ Merges all child dataframes. Only works for dataframes stored on disk - not in memory. """ hash_list = [] stack = [self] alldfs = True store = None while stack: node = stack.pop() if isinstance(node, GroupNode): stack.extend(child for _, child in sorted(node._items(), reverse=True)) else: if node._target() != TargetType.PANDAS: alldfs = False if node._store is None or node._hashes is None: msg = "Can only merge built dataframes. Build this package and try again." raise NotImplementedError(msg) node_store = node._store if store is None: store = node_store if node_store != store: raise NotImplementedError("Can only merge dataframes from the same store") hash_list += node._hashes if asa is None: if not hash_list: return None if not alldfs: raise ValueError("Group contains non-dataframe nodes") return store.load_dataframe(hash_list) else: if hash_list: assert store is not None return asa(self, [store.object_path(obj) for obj in hash_list]) else: return asa(self, [])
[ "def", "_data", "(", "self", ",", "asa", "=", "None", ")", ":", "hash_list", "=", "[", "]", "stack", "=", "[", "self", "]", "alldfs", "=", "True", "store", "=", "None", "while", "stack", ":", "node", "=", "stack", ".", "pop", "(", ")", "if", "isinstance", "(", "node", ",", "GroupNode", ")", ":", "stack", ".", "extend", "(", "child", "for", "_", ",", "child", "in", "sorted", "(", "node", ".", "_items", "(", ")", ",", "reverse", "=", "True", ")", ")", "else", ":", "if", "node", ".", "_target", "(", ")", "!=", "TargetType", ".", "PANDAS", ":", "alldfs", "=", "False", "if", "node", ".", "_store", "is", "None", "or", "node", ".", "_hashes", "is", "None", ":", "msg", "=", "\"Can only merge built dataframes. Build this package and try again.\"", "raise", "NotImplementedError", "(", "msg", ")", "node_store", "=", "node", ".", "_store", "if", "store", "is", "None", ":", "store", "=", "node_store", "if", "node_store", "!=", "store", ":", "raise", "NotImplementedError", "(", "\"Can only merge dataframes from the same store\"", ")", "hash_list", "+=", "node", ".", "_hashes", "if", "asa", "is", "None", ":", "if", "not", "hash_list", ":", "return", "None", "if", "not", "alldfs", ":", "raise", "ValueError", "(", "\"Group contains non-dataframe nodes\"", ")", "return", "store", ".", "load_dataframe", "(", "hash_list", ")", "else", ":", "if", "hash_list", ":", "assert", "store", "is", "not", "None", "return", "asa", "(", "self", ",", "[", "store", ".", "object_path", "(", "obj", ")", "for", "obj", "in", "hash_list", "]", ")", "else", ":", "return", "asa", "(", "self", ",", "[", "]", ")" ]
Merges all child dataframes. Only works for dataframes stored on disk - not in memory.
[ "Merges", "all", "child", "dataframes", ".", "Only", "works", "for", "dataframes", "stored", "on", "disk", "-", "not", "in", "memory", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/nodes.py#L184-L220
8,213
quiltdata/quilt
compiler/quilt/nodes.py
GroupNode._set
def _set(self, path, value, build_dir=''): """Create and set a node by path This creates a node from a filename or pandas DataFrame. If `value` is a filename, it must be relative to `build_dir`. `value` is stored as the export path. `build_dir` defaults to the current directory, but may be any arbitrary directory path, including an absolute path. Example: # Set `pkg.graph_image` to the data in '/home/user/bin/graph.png'. # If exported, it would export to '<export_dir>/bin/graph.png' `pkg._set(['graph_image'], 'bin/fizz.bin', '/home/user')` :param path: Path list -- I.e. ['examples', 'new_node'] :param value: Pandas dataframe, or a filename relative to build_dir :param build_dir: Directory containing `value` if value is a filename. """ assert isinstance(path, list) and len(path) > 0 if isinstance(value, pd.DataFrame): metadata = {SYSTEM_METADATA: {'target': TargetType.PANDAS.value}} elif isinstance(value, np.ndarray): metadata = {SYSTEM_METADATA: {'target': TargetType.NUMPY.value}} elif isinstance(value, string_types + (bytes,)): # bytes -> string for consistency when retrieving metadata value = value.decode() if isinstance(value, bytes) else value if os.path.isabs(value): raise ValueError("Invalid path: expected a relative path, but received {!r}".format(value)) # Security: filepath does not and should not retain the build_dir's location! metadata = {SYSTEM_METADATA: {'filepath': value, 'transform': 'id'}} if build_dir: value = os.path.join(build_dir, value) else: accepted_types = tuple(set((pd.DataFrame, np.ndarray, bytes) + string_types)) raise TypeError("Bad value type: Expected instance of any type {!r}, but received type {!r}" .format(accepted_types, type(value)), repr(value)[0:100]) for key in path: if not is_nodename(key): raise ValueError("Invalid name for node: {}".format(key)) node = self for key in path[:-1]: child = node._get(key) if not isinstance(child, GroupNode): child = GroupNode({}) node[key] = child node = child key = path[-1] node[key] = DataNode(None, None, value, metadata)
python
def _set(self, path, value, build_dir=''): """Create and set a node by path This creates a node from a filename or pandas DataFrame. If `value` is a filename, it must be relative to `build_dir`. `value` is stored as the export path. `build_dir` defaults to the current directory, but may be any arbitrary directory path, including an absolute path. Example: # Set `pkg.graph_image` to the data in '/home/user/bin/graph.png'. # If exported, it would export to '<export_dir>/bin/graph.png' `pkg._set(['graph_image'], 'bin/fizz.bin', '/home/user')` :param path: Path list -- I.e. ['examples', 'new_node'] :param value: Pandas dataframe, or a filename relative to build_dir :param build_dir: Directory containing `value` if value is a filename. """ assert isinstance(path, list) and len(path) > 0 if isinstance(value, pd.DataFrame): metadata = {SYSTEM_METADATA: {'target': TargetType.PANDAS.value}} elif isinstance(value, np.ndarray): metadata = {SYSTEM_METADATA: {'target': TargetType.NUMPY.value}} elif isinstance(value, string_types + (bytes,)): # bytes -> string for consistency when retrieving metadata value = value.decode() if isinstance(value, bytes) else value if os.path.isabs(value): raise ValueError("Invalid path: expected a relative path, but received {!r}".format(value)) # Security: filepath does not and should not retain the build_dir's location! metadata = {SYSTEM_METADATA: {'filepath': value, 'transform': 'id'}} if build_dir: value = os.path.join(build_dir, value) else: accepted_types = tuple(set((pd.DataFrame, np.ndarray, bytes) + string_types)) raise TypeError("Bad value type: Expected instance of any type {!r}, but received type {!r}" .format(accepted_types, type(value)), repr(value)[0:100]) for key in path: if not is_nodename(key): raise ValueError("Invalid name for node: {}".format(key)) node = self for key in path[:-1]: child = node._get(key) if not isinstance(child, GroupNode): child = GroupNode({}) node[key] = child node = child key = path[-1] node[key] = DataNode(None, None, value, metadata)
[ "def", "_set", "(", "self", ",", "path", ",", "value", ",", "build_dir", "=", "''", ")", ":", "assert", "isinstance", "(", "path", ",", "list", ")", "and", "len", "(", "path", ")", ">", "0", "if", "isinstance", "(", "value", ",", "pd", ".", "DataFrame", ")", ":", "metadata", "=", "{", "SYSTEM_METADATA", ":", "{", "'target'", ":", "TargetType", ".", "PANDAS", ".", "value", "}", "}", "elif", "isinstance", "(", "value", ",", "np", ".", "ndarray", ")", ":", "metadata", "=", "{", "SYSTEM_METADATA", ":", "{", "'target'", ":", "TargetType", ".", "NUMPY", ".", "value", "}", "}", "elif", "isinstance", "(", "value", ",", "string_types", "+", "(", "bytes", ",", ")", ")", ":", "# bytes -> string for consistency when retrieving metadata", "value", "=", "value", ".", "decode", "(", ")", "if", "isinstance", "(", "value", ",", "bytes", ")", "else", "value", "if", "os", ".", "path", ".", "isabs", "(", "value", ")", ":", "raise", "ValueError", "(", "\"Invalid path: expected a relative path, but received {!r}\"", ".", "format", "(", "value", ")", ")", "# Security: filepath does not and should not retain the build_dir's location!", "metadata", "=", "{", "SYSTEM_METADATA", ":", "{", "'filepath'", ":", "value", ",", "'transform'", ":", "'id'", "}", "}", "if", "build_dir", ":", "value", "=", "os", ".", "path", ".", "join", "(", "build_dir", ",", "value", ")", "else", ":", "accepted_types", "=", "tuple", "(", "set", "(", "(", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", ",", "bytes", ")", "+", "string_types", ")", ")", "raise", "TypeError", "(", "\"Bad value type: Expected instance of any type {!r}, but received type {!r}\"", ".", "format", "(", "accepted_types", ",", "type", "(", "value", ")", ")", ",", "repr", "(", "value", ")", "[", "0", ":", "100", "]", ")", "for", "key", "in", "path", ":", "if", "not", "is_nodename", "(", "key", ")", ":", "raise", "ValueError", "(", "\"Invalid name for node: {}\"", ".", "format", "(", "key", ")", ")", "node", "=", "self", "for", "key", "in", "path", "[", ":", "-", "1", "]", ":", "child", "=", "node", ".", "_get", "(", "key", ")", "if", "not", "isinstance", "(", "child", ",", "GroupNode", ")", ":", "child", "=", "GroupNode", "(", "{", "}", ")", "node", "[", "key", "]", "=", "child", "node", "=", "child", "key", "=", "path", "[", "-", "1", "]", "node", "[", "key", "]", "=", "DataNode", "(", "None", ",", "None", ",", "value", ",", "metadata", ")" ]
Create and set a node by path This creates a node from a filename or pandas DataFrame. If `value` is a filename, it must be relative to `build_dir`. `value` is stored as the export path. `build_dir` defaults to the current directory, but may be any arbitrary directory path, including an absolute path. Example: # Set `pkg.graph_image` to the data in '/home/user/bin/graph.png'. # If exported, it would export to '<export_dir>/bin/graph.png' `pkg._set(['graph_image'], 'bin/fizz.bin', '/home/user')` :param path: Path list -- I.e. ['examples', 'new_node'] :param value: Pandas dataframe, or a filename relative to build_dir :param build_dir: Directory containing `value` if value is a filename.
[ "Create", "and", "set", "a", "node", "by", "path" ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/nodes.py#L222-L276
8,214
quiltdata/quilt
registry/quilt_server/views.py
handle_api_exception
def handle_api_exception(error): """ Converts an API exception into an error response. """ _mp_track( type="exception", status_code=error.status_code, message=error.message, ) response = jsonify(dict( message=error.message )) response.status_code = error.status_code return response
python
def handle_api_exception(error): """ Converts an API exception into an error response. """ _mp_track( type="exception", status_code=error.status_code, message=error.message, ) response = jsonify(dict( message=error.message )) response.status_code = error.status_code return response
[ "def", "handle_api_exception", "(", "error", ")", ":", "_mp_track", "(", "type", "=", "\"exception\"", ",", "status_code", "=", "error", ".", "status_code", ",", "message", "=", "error", ".", "message", ",", ")", "response", "=", "jsonify", "(", "dict", "(", "message", "=", "error", ".", "message", ")", ")", "response", ".", "status_code", "=", "error", ".", "status_code", "return", "response" ]
Converts an API exception into an error response.
[ "Converts", "an", "API", "exception", "into", "an", "error", "response", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/registry/quilt_server/views.py#L188-L202
8,215
quiltdata/quilt
registry/quilt_server/views.py
api
def api(require_login=True, schema=None, enabled=True, require_admin=False, require_anonymous=False): """ Decorator for API requests. Handles auth and adds the username as the first argument. """ if require_admin: require_login = True if schema is not None: Draft4Validator.check_schema(schema) validator = Draft4Validator(schema) else: validator = None assert not (require_login and require_anonymous), ( "Can't both require login and require anonymous access.") def innerdec(f): @wraps(f) def wrapper(*args, **kwargs): g.auth = Auth(user=None, email=None, is_logged_in=False, is_admin=False, is_active=True) user_agent_str = request.headers.get('user-agent', '') g.user_agent = httpagentparser.detect(user_agent_str, fill_none=True) if not enabled: raise ApiException( requests.codes.bad_request, "This endpoint is not enabled." ) if validator is not None: try: validator.validate(request.get_json(cache=True)) except ValidationError as ex: raise ApiException(requests.codes.bad_request, ex.message) auth = request.headers.get(AUTHORIZATION_HEADER) g.auth_header = auth if auth is None: if not require_anonymous: if require_login or not ALLOW_ANONYMOUS_ACCESS: raise ApiException(requests.codes.unauthorized, "Not logged in") else: # try to validate new auth token = auth # for compatibility with old clients if token.startswith("Bearer "): token = token[7:] try: user = verify_token_string(token) except AuthException: raise ApiException(requests.codes.unauthorized, "Token invalid.") g.user = user g.auth = Auth(user=user.name, email=user.email, is_logged_in=True, is_admin=user.is_admin, is_active=user.is_active) g.auth_token = token if not g.auth.is_active: raise ApiException( requests.codes.forbidden, "Account is inactive. Must have an active account." ) if require_admin and not g.auth.is_admin: raise ApiException( requests.codes.forbidden, "Must be authenticated as an admin to use this endpoint." ) return f(*args, **kwargs) return wrapper return innerdec
python
def api(require_login=True, schema=None, enabled=True, require_admin=False, require_anonymous=False): """ Decorator for API requests. Handles auth and adds the username as the first argument. """ if require_admin: require_login = True if schema is not None: Draft4Validator.check_schema(schema) validator = Draft4Validator(schema) else: validator = None assert not (require_login and require_anonymous), ( "Can't both require login and require anonymous access.") def innerdec(f): @wraps(f) def wrapper(*args, **kwargs): g.auth = Auth(user=None, email=None, is_logged_in=False, is_admin=False, is_active=True) user_agent_str = request.headers.get('user-agent', '') g.user_agent = httpagentparser.detect(user_agent_str, fill_none=True) if not enabled: raise ApiException( requests.codes.bad_request, "This endpoint is not enabled." ) if validator is not None: try: validator.validate(request.get_json(cache=True)) except ValidationError as ex: raise ApiException(requests.codes.bad_request, ex.message) auth = request.headers.get(AUTHORIZATION_HEADER) g.auth_header = auth if auth is None: if not require_anonymous: if require_login or not ALLOW_ANONYMOUS_ACCESS: raise ApiException(requests.codes.unauthorized, "Not logged in") else: # try to validate new auth token = auth # for compatibility with old clients if token.startswith("Bearer "): token = token[7:] try: user = verify_token_string(token) except AuthException: raise ApiException(requests.codes.unauthorized, "Token invalid.") g.user = user g.auth = Auth(user=user.name, email=user.email, is_logged_in=True, is_admin=user.is_admin, is_active=user.is_active) g.auth_token = token if not g.auth.is_active: raise ApiException( requests.codes.forbidden, "Account is inactive. Must have an active account." ) if require_admin and not g.auth.is_admin: raise ApiException( requests.codes.forbidden, "Must be authenticated as an admin to use this endpoint." ) return f(*args, **kwargs) return wrapper return innerdec
[ "def", "api", "(", "require_login", "=", "True", ",", "schema", "=", "None", ",", "enabled", "=", "True", ",", "require_admin", "=", "False", ",", "require_anonymous", "=", "False", ")", ":", "if", "require_admin", ":", "require_login", "=", "True", "if", "schema", "is", "not", "None", ":", "Draft4Validator", ".", "check_schema", "(", "schema", ")", "validator", "=", "Draft4Validator", "(", "schema", ")", "else", ":", "validator", "=", "None", "assert", "not", "(", "require_login", "and", "require_anonymous", ")", ",", "(", "\"Can't both require login and require anonymous access.\"", ")", "def", "innerdec", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "g", ".", "auth", "=", "Auth", "(", "user", "=", "None", ",", "email", "=", "None", ",", "is_logged_in", "=", "False", ",", "is_admin", "=", "False", ",", "is_active", "=", "True", ")", "user_agent_str", "=", "request", ".", "headers", ".", "get", "(", "'user-agent'", ",", "''", ")", "g", ".", "user_agent", "=", "httpagentparser", ".", "detect", "(", "user_agent_str", ",", "fill_none", "=", "True", ")", "if", "not", "enabled", ":", "raise", "ApiException", "(", "requests", ".", "codes", ".", "bad_request", ",", "\"This endpoint is not enabled.\"", ")", "if", "validator", "is", "not", "None", ":", "try", ":", "validator", ".", "validate", "(", "request", ".", "get_json", "(", "cache", "=", "True", ")", ")", "except", "ValidationError", "as", "ex", ":", "raise", "ApiException", "(", "requests", ".", "codes", ".", "bad_request", ",", "ex", ".", "message", ")", "auth", "=", "request", ".", "headers", ".", "get", "(", "AUTHORIZATION_HEADER", ")", "g", ".", "auth_header", "=", "auth", "if", "auth", "is", "None", ":", "if", "not", "require_anonymous", ":", "if", "require_login", "or", "not", "ALLOW_ANONYMOUS_ACCESS", ":", "raise", "ApiException", "(", "requests", ".", "codes", ".", "unauthorized", ",", "\"Not logged in\"", ")", "else", ":", "# try to validate new auth", "token", "=", "auth", "# for compatibility with old clients", "if", "token", ".", "startswith", "(", "\"Bearer \"", ")", ":", "token", "=", "token", "[", "7", ":", "]", "try", ":", "user", "=", "verify_token_string", "(", "token", ")", "except", "AuthException", ":", "raise", "ApiException", "(", "requests", ".", "codes", ".", "unauthorized", ",", "\"Token invalid.\"", ")", "g", ".", "user", "=", "user", "g", ".", "auth", "=", "Auth", "(", "user", "=", "user", ".", "name", ",", "email", "=", "user", ".", "email", ",", "is_logged_in", "=", "True", ",", "is_admin", "=", "user", ".", "is_admin", ",", "is_active", "=", "user", ".", "is_active", ")", "g", ".", "auth_token", "=", "token", "if", "not", "g", ".", "auth", ".", "is_active", ":", "raise", "ApiException", "(", "requests", ".", "codes", ".", "forbidden", ",", "\"Account is inactive. Must have an active account.\"", ")", "if", "require_admin", "and", "not", "g", ".", "auth", ".", "is_admin", ":", "raise", "ApiException", "(", "requests", ".", "codes", ".", "forbidden", ",", "\"Must be authenticated as an admin to use this endpoint.\"", ")", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "innerdec" ]
Decorator for API requests. Handles auth and adds the username as the first argument.
[ "Decorator", "for", "API", "requests", ".", "Handles", "auth", "and", "adds", "the", "username", "as", "the", "first", "argument", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/registry/quilt_server/views.py#L204-L283
8,216
quiltdata/quilt
registry/quilt_server/views.py
_private_packages_allowed
def _private_packages_allowed(): """ Checks if the current user is allowed to create private packages. In the public cloud, the user needs to be on a paid plan. There are no restrictions in other deployments. """ if not HAVE_PAYMENTS or TEAM_ID: return True customer = _get_or_create_customer() plan = _get_customer_plan(customer) return plan != PaymentPlan.FREE
python
def _private_packages_allowed(): """ Checks if the current user is allowed to create private packages. In the public cloud, the user needs to be on a paid plan. There are no restrictions in other deployments. """ if not HAVE_PAYMENTS or TEAM_ID: return True customer = _get_or_create_customer() plan = _get_customer_plan(customer) return plan != PaymentPlan.FREE
[ "def", "_private_packages_allowed", "(", ")", ":", "if", "not", "HAVE_PAYMENTS", "or", "TEAM_ID", ":", "return", "True", "customer", "=", "_get_or_create_customer", "(", ")", "plan", "=", "_get_customer_plan", "(", "customer", ")", "return", "plan", "!=", "PaymentPlan", ".", "FREE" ]
Checks if the current user is allowed to create private packages. In the public cloud, the user needs to be on a paid plan. There are no restrictions in other deployments.
[ "Checks", "if", "the", "current", "user", "is", "allowed", "to", "create", "private", "packages", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/registry/quilt_server/views.py#L566-L578
8,217
quiltdata/quilt
compiler/quilt/tools/command.py
_create_auth
def _create_auth(team, timeout=None): """ Reads the credentials, updates the access token if necessary, and returns it. """ url = get_registry_url(team) contents = _load_auth() auth = contents.get(url) if auth is not None: # If the access token expires within a minute, update it. if auth['expires_at'] < time.time() + 60: try: auth = _update_auth(team, auth['refresh_token'], timeout) except CommandException as ex: raise CommandException( "Failed to update the access token (%s). Run `quilt login%s` again." % (ex, ' ' + team if team else '') ) contents[url] = auth _save_auth(contents) return auth
python
def _create_auth(team, timeout=None): """ Reads the credentials, updates the access token if necessary, and returns it. """ url = get_registry_url(team) contents = _load_auth() auth = contents.get(url) if auth is not None: # If the access token expires within a minute, update it. if auth['expires_at'] < time.time() + 60: try: auth = _update_auth(team, auth['refresh_token'], timeout) except CommandException as ex: raise CommandException( "Failed to update the access token (%s). Run `quilt login%s` again." % (ex, ' ' + team if team else '') ) contents[url] = auth _save_auth(contents) return auth
[ "def", "_create_auth", "(", "team", ",", "timeout", "=", "None", ")", ":", "url", "=", "get_registry_url", "(", "team", ")", "contents", "=", "_load_auth", "(", ")", "auth", "=", "contents", ".", "get", "(", "url", ")", "if", "auth", "is", "not", "None", ":", "# If the access token expires within a minute, update it.", "if", "auth", "[", "'expires_at'", "]", "<", "time", ".", "time", "(", ")", "+", "60", ":", "try", ":", "auth", "=", "_update_auth", "(", "team", ",", "auth", "[", "'refresh_token'", "]", ",", "timeout", ")", "except", "CommandException", "as", "ex", ":", "raise", "CommandException", "(", "\"Failed to update the access token (%s). Run `quilt login%s` again.\"", "%", "(", "ex", ",", "' '", "+", "team", "if", "team", "else", "''", ")", ")", "contents", "[", "url", "]", "=", "auth", "_save_auth", "(", "contents", ")", "return", "auth" ]
Reads the credentials, updates the access token if necessary, and returns it.
[ "Reads", "the", "credentials", "updates", "the", "access", "token", "if", "necessary", "and", "returns", "it", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L227-L248
8,218
quiltdata/quilt
compiler/quilt/tools/command.py
_create_session
def _create_session(team, auth): """ Creates a session object to be used for `push`, `install`, etc. """ session = requests.Session() session.hooks.update(dict( response=partial(_handle_response, team) )) session.headers.update({ "Content-Type": "application/json", "Accept": "application/json", "User-Agent": "quilt-cli/%s (%s %s) %s/%s" % ( VERSION, platform.system(), platform.release(), platform.python_implementation(), platform.python_version() ) }) if auth is not None: session.headers["Authorization"] = "Bearer %s" % auth['access_token'] return session
python
def _create_session(team, auth): """ Creates a session object to be used for `push`, `install`, etc. """ session = requests.Session() session.hooks.update(dict( response=partial(_handle_response, team) )) session.headers.update({ "Content-Type": "application/json", "Accept": "application/json", "User-Agent": "quilt-cli/%s (%s %s) %s/%s" % ( VERSION, platform.system(), platform.release(), platform.python_implementation(), platform.python_version() ) }) if auth is not None: session.headers["Authorization"] = "Bearer %s" % auth['access_token'] return session
[ "def", "_create_session", "(", "team", ",", "auth", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "session", ".", "hooks", ".", "update", "(", "dict", "(", "response", "=", "partial", "(", "_handle_response", ",", "team", ")", ")", ")", "session", ".", "headers", ".", "update", "(", "{", "\"Content-Type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"application/json\"", ",", "\"User-Agent\"", ":", "\"quilt-cli/%s (%s %s) %s/%s\"", "%", "(", "VERSION", ",", "platform", ".", "system", "(", ")", ",", "platform", ".", "release", "(", ")", ",", "platform", ".", "python_implementation", "(", ")", ",", "platform", ".", "python_version", "(", ")", ")", "}", ")", "if", "auth", "is", "not", "None", ":", "session", ".", "headers", "[", "\"Authorization\"", "]", "=", "\"Bearer %s\"", "%", "auth", "[", "'access_token'", "]", "return", "session" ]
Creates a session object to be used for `push`, `install`, etc.
[ "Creates", "a", "session", "object", "to", "be", "used", "for", "push", "install", "etc", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L250-L269
8,219
quiltdata/quilt
compiler/quilt/tools/command.py
_get_session
def _get_session(team, timeout=None): """ Creates a session or returns an existing session. """ global _sessions # pylint:disable=C0103 session = _sessions.get(team) if session is None: auth = _create_auth(team, timeout) _sessions[team] = session = _create_session(team, auth) assert session is not None return session
python
def _get_session(team, timeout=None): """ Creates a session or returns an existing session. """ global _sessions # pylint:disable=C0103 session = _sessions.get(team) if session is None: auth = _create_auth(team, timeout) _sessions[team] = session = _create_session(team, auth) assert session is not None return session
[ "def", "_get_session", "(", "team", ",", "timeout", "=", "None", ")", ":", "global", "_sessions", "# pylint:disable=C0103", "session", "=", "_sessions", ".", "get", "(", "team", ")", "if", "session", "is", "None", ":", "auth", "=", "_create_auth", "(", "team", ",", "timeout", ")", "_sessions", "[", "team", "]", "=", "session", "=", "_create_session", "(", "team", ",", "auth", ")", "assert", "session", "is", "not", "None", "return", "session" ]
Creates a session or returns an existing session.
[ "Creates", "a", "session", "or", "returns", "an", "existing", "session", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L273-L285
8,220
quiltdata/quilt
compiler/quilt/tools/command.py
_check_team_login
def _check_team_login(team): """ Disallow simultaneous public cloud and team logins. """ contents = _load_auth() for auth in itervalues(contents): existing_team = auth.get('team') if team and team != existing_team: raise CommandException( "Can't log in as team %r; log out first." % team ) elif not team and existing_team: raise CommandException( "Can't log in as a public user; log out from team %r first." % existing_team )
python
def _check_team_login(team): """ Disallow simultaneous public cloud and team logins. """ contents = _load_auth() for auth in itervalues(contents): existing_team = auth.get('team') if team and team != existing_team: raise CommandException( "Can't log in as team %r; log out first." % team ) elif not team and existing_team: raise CommandException( "Can't log in as a public user; log out from team %r first." % existing_team )
[ "def", "_check_team_login", "(", "team", ")", ":", "contents", "=", "_load_auth", "(", ")", "for", "auth", "in", "itervalues", "(", "contents", ")", ":", "existing_team", "=", "auth", ".", "get", "(", "'team'", ")", "if", "team", "and", "team", "!=", "existing_team", ":", "raise", "CommandException", "(", "\"Can't log in as team %r; log out first.\"", "%", "team", ")", "elif", "not", "team", "and", "existing_team", ":", "raise", "CommandException", "(", "\"Can't log in as a public user; log out from team %r first.\"", "%", "existing_team", ")" ]
Disallow simultaneous public cloud and team logins.
[ "Disallow", "simultaneous", "public", "cloud", "and", "team", "logins", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L351-L366
8,221
quiltdata/quilt
compiler/quilt/tools/command.py
_check_team_exists
def _check_team_exists(team): """ Check that the team registry actually exists. """ if team is None: return hostname = urlparse(get_registry_url(team)).hostname try: socket.gethostbyname(hostname) except IOError: try: # Do we have internet? socket.gethostbyname('quiltdata.com') except IOError: message = "Can't find quiltdata.com. Check your internet connection." else: message = "Unable to connect to registry. Is the team name %r correct?" % team raise CommandException(message)
python
def _check_team_exists(team): """ Check that the team registry actually exists. """ if team is None: return hostname = urlparse(get_registry_url(team)).hostname try: socket.gethostbyname(hostname) except IOError: try: # Do we have internet? socket.gethostbyname('quiltdata.com') except IOError: message = "Can't find quiltdata.com. Check your internet connection." else: message = "Unable to connect to registry. Is the team name %r correct?" % team raise CommandException(message)
[ "def", "_check_team_exists", "(", "team", ")", ":", "if", "team", "is", "None", ":", "return", "hostname", "=", "urlparse", "(", "get_registry_url", "(", "team", ")", ")", ".", "hostname", "try", ":", "socket", ".", "gethostbyname", "(", "hostname", ")", "except", "IOError", ":", "try", ":", "# Do we have internet?", "socket", ".", "gethostbyname", "(", "'quiltdata.com'", ")", "except", "IOError", ":", "message", "=", "\"Can't find quiltdata.com. Check your internet connection.\"", "else", ":", "message", "=", "\"Unable to connect to registry. Is the team name %r correct?\"", "%", "team", "raise", "CommandException", "(", "message", ")" ]
Check that the team registry actually exists.
[ "Check", "that", "the", "team", "registry", "actually", "exists", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L375-L393
8,222
quiltdata/quilt
compiler/quilt/tools/command.py
login_with_token
def login_with_token(refresh_token, team=None): """ Authenticate using an existing token. """ # Get an access token and a new refresh token. _check_team_id(team) auth = _update_auth(team, refresh_token) url = get_registry_url(team) contents = _load_auth() contents[url] = auth _save_auth(contents) _clear_session(team)
python
def login_with_token(refresh_token, team=None): """ Authenticate using an existing token. """ # Get an access token and a new refresh token. _check_team_id(team) auth = _update_auth(team, refresh_token) url = get_registry_url(team) contents = _load_auth() contents[url] = auth _save_auth(contents) _clear_session(team)
[ "def", "login_with_token", "(", "refresh_token", ",", "team", "=", "None", ")", ":", "# Get an access token and a new refresh token.", "_check_team_id", "(", "team", ")", "auth", "=", "_update_auth", "(", "team", ",", "refresh_token", ")", "url", "=", "get_registry_url", "(", "team", ")", "contents", "=", "_load_auth", "(", ")", "contents", "[", "url", "]", "=", "auth", "_save_auth", "(", "contents", ")", "_clear_session", "(", "team", ")" ]
Authenticate using an existing token.
[ "Authenticate", "using", "an", "existing", "token", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L417-L430
8,223
quiltdata/quilt
compiler/quilt/tools/command.py
generate
def generate(directory, outfilename=DEFAULT_BUILDFILE): """ Generate a build-file for quilt build from a directory of source files. """ try: buildfilepath = generate_build_file(directory, outfilename=outfilename) except BuildException as builderror: raise CommandException(str(builderror)) print("Generated build-file %s." % (buildfilepath))
python
def generate(directory, outfilename=DEFAULT_BUILDFILE): """ Generate a build-file for quilt build from a directory of source files. """ try: buildfilepath = generate_build_file(directory, outfilename=outfilename) except BuildException as builderror: raise CommandException(str(builderror)) print("Generated build-file %s." % (buildfilepath))
[ "def", "generate", "(", "directory", ",", "outfilename", "=", "DEFAULT_BUILDFILE", ")", ":", "try", ":", "buildfilepath", "=", "generate_build_file", "(", "directory", ",", "outfilename", "=", "outfilename", ")", "except", "BuildException", "as", "builderror", ":", "raise", "CommandException", "(", "str", "(", "builderror", ")", ")", "print", "(", "\"Generated build-file %s.\"", "%", "(", "buildfilepath", ")", ")" ]
Generate a build-file for quilt build from a directory of source files.
[ "Generate", "a", "build", "-", "file", "for", "quilt", "build", "from", "a", "directory", "of", "source", "files", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L445-L455
8,224
quiltdata/quilt
compiler/quilt/tools/command.py
build
def build(package, path=None, dry_run=False, env='default', force=False, build_file=False): """ Compile a Quilt data package, either from a build file or an existing package node. :param package: short package specifier, i.e. 'team:user/pkg' :param path: file path, git url, or existing package node """ # TODO: rename 'path' param to 'target'? team, _, _, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) logged_in_team = _find_logged_in_team() if logged_in_team is not None and team is None and force is False: answer = input("You're logged in as a team member, but you aren't specifying " "a team for the package you're currently building. Maybe you meant:\n" "quilt build {team}:{package}\n" "Are you sure you want to continue? (y/N) ".format( team=logged_in_team, package=package)) if answer.lower() != 'y': return # Backward compatibility: if there's no subpath, we're building a top-level package, # so treat `path` as a build file, not as a data node. if not subpath: build_file = True package_hash = hashlib.md5(package.encode('utf-8')).hexdigest() try: _build_internal(package, path, dry_run, env, build_file) except Exception as ex: _log(team, type='build', package=package_hash, dry_run=dry_run, env=env, error=str(ex)) raise _log(team, type='build', package=package_hash, dry_run=dry_run, env=env)
python
def build(package, path=None, dry_run=False, env='default', force=False, build_file=False): """ Compile a Quilt data package, either from a build file or an existing package node. :param package: short package specifier, i.e. 'team:user/pkg' :param path: file path, git url, or existing package node """ # TODO: rename 'path' param to 'target'? team, _, _, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) logged_in_team = _find_logged_in_team() if logged_in_team is not None and team is None and force is False: answer = input("You're logged in as a team member, but you aren't specifying " "a team for the package you're currently building. Maybe you meant:\n" "quilt build {team}:{package}\n" "Are you sure you want to continue? (y/N) ".format( team=logged_in_team, package=package)) if answer.lower() != 'y': return # Backward compatibility: if there's no subpath, we're building a top-level package, # so treat `path` as a build file, not as a data node. if not subpath: build_file = True package_hash = hashlib.md5(package.encode('utf-8')).hexdigest() try: _build_internal(package, path, dry_run, env, build_file) except Exception as ex: _log(team, type='build', package=package_hash, dry_run=dry_run, env=env, error=str(ex)) raise _log(team, type='build', package=package_hash, dry_run=dry_run, env=env)
[ "def", "build", "(", "package", ",", "path", "=", "None", ",", "dry_run", "=", "False", ",", "env", "=", "'default'", ",", "force", "=", "False", ",", "build_file", "=", "False", ")", ":", "# TODO: rename 'path' param to 'target'?", "team", ",", "_", ",", "_", ",", "subpath", "=", "parse_package", "(", "package", ",", "allow_subpath", "=", "True", ")", "_check_team_id", "(", "team", ")", "logged_in_team", "=", "_find_logged_in_team", "(", ")", "if", "logged_in_team", "is", "not", "None", "and", "team", "is", "None", "and", "force", "is", "False", ":", "answer", "=", "input", "(", "\"You're logged in as a team member, but you aren't specifying \"", "\"a team for the package you're currently building. Maybe you meant:\\n\"", "\"quilt build {team}:{package}\\n\"", "\"Are you sure you want to continue? (y/N) \"", ".", "format", "(", "team", "=", "logged_in_team", ",", "package", "=", "package", ")", ")", "if", "answer", ".", "lower", "(", ")", "!=", "'y'", ":", "return", "# Backward compatibility: if there's no subpath, we're building a top-level package,", "# so treat `path` as a build file, not as a data node.", "if", "not", "subpath", ":", "build_file", "=", "True", "package_hash", "=", "hashlib", ".", "md5", "(", "package", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "try", ":", "_build_internal", "(", "package", ",", "path", ",", "dry_run", ",", "env", ",", "build_file", ")", "except", "Exception", "as", "ex", ":", "_log", "(", "team", ",", "type", "=", "'build'", ",", "package", "=", "package_hash", ",", "dry_run", "=", "dry_run", ",", "env", "=", "env", ",", "error", "=", "str", "(", "ex", ")", ")", "raise", "_log", "(", "team", ",", "type", "=", "'build'", ",", "package", "=", "package_hash", ",", "dry_run", "=", "dry_run", ",", "env", "=", "env", ")" ]
Compile a Quilt data package, either from a build file or an existing package node. :param package: short package specifier, i.e. 'team:user/pkg' :param path: file path, git url, or existing package node
[ "Compile", "a", "Quilt", "data", "package", "either", "from", "a", "build", "file", "or", "an", "existing", "package", "node", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L502-L533
8,225
quiltdata/quilt
compiler/quilt/tools/command.py
build_from_node
def build_from_node(package, node): """ Compile a Quilt data package from an existing package node. """ team, owner, pkg, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) store = PackageStore() pkg_root = get_or_create_package(store, team, owner, pkg, subpath) if not subpath and not isinstance(node, nodes.GroupNode): raise CommandException("Top-level node must be a group") def _process_node(node, path): if not isinstance(node._meta, dict): raise CommandException( "Error in %s: value must be a dictionary" % '.'.join(path + ['_meta']) ) meta = dict(node._meta) system_meta = meta.pop(SYSTEM_METADATA, {}) if not isinstance(system_meta, dict): raise CommandException( "Error in %s: %s overwritten. %s is a reserved metadata key. Try a different key." % ('.'.join(path + ['_meta']), SYSTEM_METADATA, SYSTEM_METADATA) ) if isinstance(node, nodes.GroupNode): store.add_to_package_group(pkg_root, path, meta) for key, child in node._items(): _process_node(child, path + [key]) elif isinstance(node, nodes.DataNode): # TODO: Reuse existing fragments if we have them. data = node._data() filepath = system_meta.get('filepath') transform = system_meta.get('transform') if isinstance(data, pd.DataFrame): store.add_to_package_df(pkg_root, data, path, TargetType.PANDAS, filepath, transform, meta) elif isinstance(data, np.ndarray): store.add_to_package_numpy(pkg_root, data, path, TargetType.NUMPY, filepath, transform, meta) elif isinstance(data, string_types): store.add_to_package_file(pkg_root, data, path, TargetType.FILE, filepath, transform, meta) else: assert False, "Unexpected data type: %r" % data else: assert False, "Unexpected node type: %r" % node try: _process_node(node, subpath) except StoreException as ex: raise CommandException("Failed to build the package: %s" % ex) store.save_package_contents(pkg_root, team, owner, pkg)
python
def build_from_node(package, node): """ Compile a Quilt data package from an existing package node. """ team, owner, pkg, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) store = PackageStore() pkg_root = get_or_create_package(store, team, owner, pkg, subpath) if not subpath and not isinstance(node, nodes.GroupNode): raise CommandException("Top-level node must be a group") def _process_node(node, path): if not isinstance(node._meta, dict): raise CommandException( "Error in %s: value must be a dictionary" % '.'.join(path + ['_meta']) ) meta = dict(node._meta) system_meta = meta.pop(SYSTEM_METADATA, {}) if not isinstance(system_meta, dict): raise CommandException( "Error in %s: %s overwritten. %s is a reserved metadata key. Try a different key." % ('.'.join(path + ['_meta']), SYSTEM_METADATA, SYSTEM_METADATA) ) if isinstance(node, nodes.GroupNode): store.add_to_package_group(pkg_root, path, meta) for key, child in node._items(): _process_node(child, path + [key]) elif isinstance(node, nodes.DataNode): # TODO: Reuse existing fragments if we have them. data = node._data() filepath = system_meta.get('filepath') transform = system_meta.get('transform') if isinstance(data, pd.DataFrame): store.add_to_package_df(pkg_root, data, path, TargetType.PANDAS, filepath, transform, meta) elif isinstance(data, np.ndarray): store.add_to_package_numpy(pkg_root, data, path, TargetType.NUMPY, filepath, transform, meta) elif isinstance(data, string_types): store.add_to_package_file(pkg_root, data, path, TargetType.FILE, filepath, transform, meta) else: assert False, "Unexpected data type: %r" % data else: assert False, "Unexpected node type: %r" % node try: _process_node(node, subpath) except StoreException as ex: raise CommandException("Failed to build the package: %s" % ex) store.save_package_contents(pkg_root, team, owner, pkg)
[ "def", "build_from_node", "(", "package", ",", "node", ")", ":", "team", ",", "owner", ",", "pkg", ",", "subpath", "=", "parse_package", "(", "package", ",", "allow_subpath", "=", "True", ")", "_check_team_id", "(", "team", ")", "store", "=", "PackageStore", "(", ")", "pkg_root", "=", "get_or_create_package", "(", "store", ",", "team", ",", "owner", ",", "pkg", ",", "subpath", ")", "if", "not", "subpath", "and", "not", "isinstance", "(", "node", ",", "nodes", ".", "GroupNode", ")", ":", "raise", "CommandException", "(", "\"Top-level node must be a group\"", ")", "def", "_process_node", "(", "node", ",", "path", ")", ":", "if", "not", "isinstance", "(", "node", ".", "_meta", ",", "dict", ")", ":", "raise", "CommandException", "(", "\"Error in %s: value must be a dictionary\"", "%", "'.'", ".", "join", "(", "path", "+", "[", "'_meta'", "]", ")", ")", "meta", "=", "dict", "(", "node", ".", "_meta", ")", "system_meta", "=", "meta", ".", "pop", "(", "SYSTEM_METADATA", ",", "{", "}", ")", "if", "not", "isinstance", "(", "system_meta", ",", "dict", ")", ":", "raise", "CommandException", "(", "\"Error in %s: %s overwritten. %s is a reserved metadata key. Try a different key.\"", "%", "(", "'.'", ".", "join", "(", "path", "+", "[", "'_meta'", "]", ")", ",", "SYSTEM_METADATA", ",", "SYSTEM_METADATA", ")", ")", "if", "isinstance", "(", "node", ",", "nodes", ".", "GroupNode", ")", ":", "store", ".", "add_to_package_group", "(", "pkg_root", ",", "path", ",", "meta", ")", "for", "key", ",", "child", "in", "node", ".", "_items", "(", ")", ":", "_process_node", "(", "child", ",", "path", "+", "[", "key", "]", ")", "elif", "isinstance", "(", "node", ",", "nodes", ".", "DataNode", ")", ":", "# TODO: Reuse existing fragments if we have them.", "data", "=", "node", ".", "_data", "(", ")", "filepath", "=", "system_meta", ".", "get", "(", "'filepath'", ")", "transform", "=", "system_meta", ".", "get", "(", "'transform'", ")", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "store", ".", "add_to_package_df", "(", "pkg_root", ",", "data", ",", "path", ",", "TargetType", ".", "PANDAS", ",", "filepath", ",", "transform", ",", "meta", ")", "elif", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", ":", "store", ".", "add_to_package_numpy", "(", "pkg_root", ",", "data", ",", "path", ",", "TargetType", ".", "NUMPY", ",", "filepath", ",", "transform", ",", "meta", ")", "elif", "isinstance", "(", "data", ",", "string_types", ")", ":", "store", ".", "add_to_package_file", "(", "pkg_root", ",", "data", ",", "path", ",", "TargetType", ".", "FILE", ",", "filepath", ",", "transform", ",", "meta", ")", "else", ":", "assert", "False", ",", "\"Unexpected data type: %r\"", "%", "data", "else", ":", "assert", "False", ",", "\"Unexpected node type: %r\"", "%", "node", "try", ":", "_process_node", "(", "node", ",", "subpath", ")", "except", "StoreException", "as", "ex", ":", "raise", "CommandException", "(", "\"Failed to build the package: %s\"", "%", "ex", ")", "store", ".", "save_package_contents", "(", "pkg_root", ",", "team", ",", "owner", ",", "pkg", ")" ]
Compile a Quilt data package from an existing package node.
[ "Compile", "a", "Quilt", "data", "package", "from", "an", "existing", "package", "node", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L568-L618
8,226
quiltdata/quilt
compiler/quilt/tools/command.py
build_from_path
def build_from_path(package, path, dry_run=False, env='default', outfilename=DEFAULT_BUILDFILE): """ Compile a Quilt data package from a build file. Path can be a directory, in which case the build file will be generated automatically. """ team, owner, pkg, subpath = parse_package(package, allow_subpath=True) if not os.path.exists(path): raise CommandException("%s does not exist." % path) try: if os.path.isdir(path): buildpath = os.path.join(path, outfilename) if os.path.exists(buildpath): raise CommandException( "Build file already exists. Run `quilt build %r` instead." % buildpath ) contents = generate_contents(path, outfilename) build_package_from_contents(team, owner, pkg, subpath, path, contents, dry_run=dry_run, env=env) else: build_package(team, owner, pkg, subpath, path, dry_run=dry_run, env=env) if not dry_run: print("Built %s successfully." % package) except BuildException as ex: raise CommandException("Failed to build the package: %s" % ex)
python
def build_from_path(package, path, dry_run=False, env='default', outfilename=DEFAULT_BUILDFILE): """ Compile a Quilt data package from a build file. Path can be a directory, in which case the build file will be generated automatically. """ team, owner, pkg, subpath = parse_package(package, allow_subpath=True) if not os.path.exists(path): raise CommandException("%s does not exist." % path) try: if os.path.isdir(path): buildpath = os.path.join(path, outfilename) if os.path.exists(buildpath): raise CommandException( "Build file already exists. Run `quilt build %r` instead." % buildpath ) contents = generate_contents(path, outfilename) build_package_from_contents(team, owner, pkg, subpath, path, contents, dry_run=dry_run, env=env) else: build_package(team, owner, pkg, subpath, path, dry_run=dry_run, env=env) if not dry_run: print("Built %s successfully." % package) except BuildException as ex: raise CommandException("Failed to build the package: %s" % ex)
[ "def", "build_from_path", "(", "package", ",", "path", ",", "dry_run", "=", "False", ",", "env", "=", "'default'", ",", "outfilename", "=", "DEFAULT_BUILDFILE", ")", ":", "team", ",", "owner", ",", "pkg", ",", "subpath", "=", "parse_package", "(", "package", ",", "allow_subpath", "=", "True", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "CommandException", "(", "\"%s does not exist.\"", "%", "path", ")", "try", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "buildpath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "outfilename", ")", "if", "os", ".", "path", ".", "exists", "(", "buildpath", ")", ":", "raise", "CommandException", "(", "\"Build file already exists. Run `quilt build %r` instead.\"", "%", "buildpath", ")", "contents", "=", "generate_contents", "(", "path", ",", "outfilename", ")", "build_package_from_contents", "(", "team", ",", "owner", ",", "pkg", ",", "subpath", ",", "path", ",", "contents", ",", "dry_run", "=", "dry_run", ",", "env", "=", "env", ")", "else", ":", "build_package", "(", "team", ",", "owner", ",", "pkg", ",", "subpath", ",", "path", ",", "dry_run", "=", "dry_run", ",", "env", "=", "env", ")", "if", "not", "dry_run", ":", "print", "(", "\"Built %s successfully.\"", "%", "package", ")", "except", "BuildException", "as", "ex", ":", "raise", "CommandException", "(", "\"Failed to build the package: %s\"", "%", "ex", ")" ]
Compile a Quilt data package from a build file. Path can be a directory, in which case the build file will be generated automatically.
[ "Compile", "a", "Quilt", "data", "package", "from", "a", "build", "file", ".", "Path", "can", "be", "a", "directory", "in", "which", "case", "the", "build", "file", "will", "be", "generated", "automatically", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L620-L646
8,227
quiltdata/quilt
compiler/quilt/tools/command.py
log
def log(package): """ List all of the changes to a package on the server. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/log/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg ) ) table = [("Hash", "Pushed", "Author", "Tags", "Versions")] for entry in reversed(response.json()['logs']): ugly = datetime.fromtimestamp(entry['created']) nice = ugly.strftime("%Y-%m-%d %H:%M:%S") table.append((entry['hash'], nice, entry['author'], str(entry.get('tags', [])), str(entry.get('versions', [])))) _print_table(table)
python
def log(package): """ List all of the changes to a package on the server. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/log/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg ) ) table = [("Hash", "Pushed", "Author", "Tags", "Versions")] for entry in reversed(response.json()['logs']): ugly = datetime.fromtimestamp(entry['created']) nice = ugly.strftime("%Y-%m-%d %H:%M:%S") table.append((entry['hash'], nice, entry['author'], str(entry.get('tags', [])), str(entry.get('versions', [])))) _print_table(table)
[ "def", "log", "(", "package", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "session", "=", "_get_session", "(", "team", ")", "response", "=", "session", ".", "get", "(", "\"{url}/api/log/{owner}/{pkg}/\"", ".", "format", "(", "url", "=", "get_registry_url", "(", "team", ")", ",", "owner", "=", "owner", ",", "pkg", "=", "pkg", ")", ")", "table", "=", "[", "(", "\"Hash\"", ",", "\"Pushed\"", ",", "\"Author\"", ",", "\"Tags\"", ",", "\"Versions\"", ")", "]", "for", "entry", "in", "reversed", "(", "response", ".", "json", "(", ")", "[", "'logs'", "]", ")", ":", "ugly", "=", "datetime", ".", "fromtimestamp", "(", "entry", "[", "'created'", "]", ")", "nice", "=", "ugly", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ")", "table", ".", "append", "(", "(", "entry", "[", "'hash'", "]", ",", "nice", ",", "entry", "[", "'author'", "]", ",", "str", "(", "entry", ".", "get", "(", "'tags'", ",", "[", "]", ")", ")", ",", "str", "(", "entry", ".", "get", "(", "'versions'", ",", "[", "]", ")", ")", ")", ")", "_print_table", "(", "table", ")" ]
List all of the changes to a package on the server.
[ "List", "all", "of", "the", "changes", "to", "a", "package", "on", "the", "server", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L648-L669
8,228
quiltdata/quilt
compiler/quilt/tools/command.py
push
def push(package, is_public=False, is_team=False, reupload=False, hash=None): """ Push a Quilt data package to the server """ team, owner, pkg, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) session = _get_session(team) store, pkgroot = PackageStore.find_package(team, owner, pkg, pkghash=hash) if pkgroot is None: raise CommandException("Package {package} not found.".format(package=package)) pkghash = hash_contents(pkgroot) if hash is not None: assert pkghash == hash contents = pkgroot for component in subpath: try: contents = contents.children[component] except (AttributeError, KeyError): raise CommandException("Invalid subpath: %r" % component) def _push_package(dry_run=False, sizes=dict()): data = json.dumps(dict( dry_run=dry_run, is_public=is_public, is_team=is_team, contents=contents, description="", # TODO sizes=sizes ), default=encode_node) compressed_data = gzip_compress(data.encode('utf-8')) if subpath: return session.post( "{url}/api/package_update/{owner}/{pkg}/{subpath}".format( url=get_registry_url(team), owner=owner, pkg=pkg, subpath='/'.join(subpath) ), data=compressed_data, headers={ 'Content-Encoding': 'gzip' } ) else: return session.put( "{url}/api/package/{owner}/{pkg}/{hash}".format( url=get_registry_url(team), owner=owner, pkg=pkg, hash=pkghash ), data=compressed_data, headers={ 'Content-Encoding': 'gzip' } ) print("Fetching upload URLs from the registry...") resp = _push_package(dry_run=True) obj_urls = resp.json()['upload_urls'] assert set(obj_urls) == set(find_object_hashes(contents)) obj_sizes = { obj_hash: os.path.getsize(store.object_path(obj_hash)) for obj_hash in obj_urls } success = upload_fragments(store, obj_urls, obj_sizes, reupload=reupload) if not success: raise CommandException("Failed to upload fragments") print("Uploading package metadata...") resp = _push_package(sizes=obj_sizes) package_url = resp.json()['package_url'] if not subpath: # Update the latest tag. print("Updating the 'latest' tag...") session.put( "{url}/api/tag/{owner}/{pkg}/{tag}".format( url=get_registry_url(team), owner=owner, pkg=pkg, tag=LATEST_TAG ), data=json.dumps(dict( hash=pkghash )) ) print("Push complete. %s is live:\n%s" % (package, package_url))
python
def push(package, is_public=False, is_team=False, reupload=False, hash=None): """ Push a Quilt data package to the server """ team, owner, pkg, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) session = _get_session(team) store, pkgroot = PackageStore.find_package(team, owner, pkg, pkghash=hash) if pkgroot is None: raise CommandException("Package {package} not found.".format(package=package)) pkghash = hash_contents(pkgroot) if hash is not None: assert pkghash == hash contents = pkgroot for component in subpath: try: contents = contents.children[component] except (AttributeError, KeyError): raise CommandException("Invalid subpath: %r" % component) def _push_package(dry_run=False, sizes=dict()): data = json.dumps(dict( dry_run=dry_run, is_public=is_public, is_team=is_team, contents=contents, description="", # TODO sizes=sizes ), default=encode_node) compressed_data = gzip_compress(data.encode('utf-8')) if subpath: return session.post( "{url}/api/package_update/{owner}/{pkg}/{subpath}".format( url=get_registry_url(team), owner=owner, pkg=pkg, subpath='/'.join(subpath) ), data=compressed_data, headers={ 'Content-Encoding': 'gzip' } ) else: return session.put( "{url}/api/package/{owner}/{pkg}/{hash}".format( url=get_registry_url(team), owner=owner, pkg=pkg, hash=pkghash ), data=compressed_data, headers={ 'Content-Encoding': 'gzip' } ) print("Fetching upload URLs from the registry...") resp = _push_package(dry_run=True) obj_urls = resp.json()['upload_urls'] assert set(obj_urls) == set(find_object_hashes(contents)) obj_sizes = { obj_hash: os.path.getsize(store.object_path(obj_hash)) for obj_hash in obj_urls } success = upload_fragments(store, obj_urls, obj_sizes, reupload=reupload) if not success: raise CommandException("Failed to upload fragments") print("Uploading package metadata...") resp = _push_package(sizes=obj_sizes) package_url = resp.json()['package_url'] if not subpath: # Update the latest tag. print("Updating the 'latest' tag...") session.put( "{url}/api/tag/{owner}/{pkg}/{tag}".format( url=get_registry_url(team), owner=owner, pkg=pkg, tag=LATEST_TAG ), data=json.dumps(dict( hash=pkghash )) ) print("Push complete. %s is live:\n%s" % (package, package_url))
[ "def", "push", "(", "package", ",", "is_public", "=", "False", ",", "is_team", "=", "False", ",", "reupload", "=", "False", ",", "hash", "=", "None", ")", ":", "team", ",", "owner", ",", "pkg", ",", "subpath", "=", "parse_package", "(", "package", ",", "allow_subpath", "=", "True", ")", "_check_team_id", "(", "team", ")", "session", "=", "_get_session", "(", "team", ")", "store", ",", "pkgroot", "=", "PackageStore", ".", "find_package", "(", "team", ",", "owner", ",", "pkg", ",", "pkghash", "=", "hash", ")", "if", "pkgroot", "is", "None", ":", "raise", "CommandException", "(", "\"Package {package} not found.\"", ".", "format", "(", "package", "=", "package", ")", ")", "pkghash", "=", "hash_contents", "(", "pkgroot", ")", "if", "hash", "is", "not", "None", ":", "assert", "pkghash", "==", "hash", "contents", "=", "pkgroot", "for", "component", "in", "subpath", ":", "try", ":", "contents", "=", "contents", ".", "children", "[", "component", "]", "except", "(", "AttributeError", ",", "KeyError", ")", ":", "raise", "CommandException", "(", "\"Invalid subpath: %r\"", "%", "component", ")", "def", "_push_package", "(", "dry_run", "=", "False", ",", "sizes", "=", "dict", "(", ")", ")", ":", "data", "=", "json", ".", "dumps", "(", "dict", "(", "dry_run", "=", "dry_run", ",", "is_public", "=", "is_public", ",", "is_team", "=", "is_team", ",", "contents", "=", "contents", ",", "description", "=", "\"\"", ",", "# TODO", "sizes", "=", "sizes", ")", ",", "default", "=", "encode_node", ")", "compressed_data", "=", "gzip_compress", "(", "data", ".", "encode", "(", "'utf-8'", ")", ")", "if", "subpath", ":", "return", "session", ".", "post", "(", "\"{url}/api/package_update/{owner}/{pkg}/{subpath}\"", ".", "format", "(", "url", "=", "get_registry_url", "(", "team", ")", ",", "owner", "=", "owner", ",", "pkg", "=", "pkg", ",", "subpath", "=", "'/'", ".", "join", "(", "subpath", ")", ")", ",", "data", "=", "compressed_data", ",", "headers", "=", "{", "'Content-Encoding'", ":", "'gzip'", "}", ")", "else", ":", "return", "session", ".", "put", "(", "\"{url}/api/package/{owner}/{pkg}/{hash}\"", ".", "format", "(", "url", "=", "get_registry_url", "(", "team", ")", ",", "owner", "=", "owner", ",", "pkg", "=", "pkg", ",", "hash", "=", "pkghash", ")", ",", "data", "=", "compressed_data", ",", "headers", "=", "{", "'Content-Encoding'", ":", "'gzip'", "}", ")", "print", "(", "\"Fetching upload URLs from the registry...\"", ")", "resp", "=", "_push_package", "(", "dry_run", "=", "True", ")", "obj_urls", "=", "resp", ".", "json", "(", ")", "[", "'upload_urls'", "]", "assert", "set", "(", "obj_urls", ")", "==", "set", "(", "find_object_hashes", "(", "contents", ")", ")", "obj_sizes", "=", "{", "obj_hash", ":", "os", ".", "path", ".", "getsize", "(", "store", ".", "object_path", "(", "obj_hash", ")", ")", "for", "obj_hash", "in", "obj_urls", "}", "success", "=", "upload_fragments", "(", "store", ",", "obj_urls", ",", "obj_sizes", ",", "reupload", "=", "reupload", ")", "if", "not", "success", ":", "raise", "CommandException", "(", "\"Failed to upload fragments\"", ")", "print", "(", "\"Uploading package metadata...\"", ")", "resp", "=", "_push_package", "(", "sizes", "=", "obj_sizes", ")", "package_url", "=", "resp", ".", "json", "(", ")", "[", "'package_url'", "]", "if", "not", "subpath", ":", "# Update the latest tag.", "print", "(", "\"Updating the 'latest' tag...\"", ")", "session", ".", "put", "(", "\"{url}/api/tag/{owner}/{pkg}/{tag}\"", ".", "format", "(", "url", "=", "get_registry_url", "(", "team", ")", ",", "owner", "=", "owner", ",", "pkg", "=", "pkg", ",", "tag", "=", "LATEST_TAG", ")", ",", "data", "=", "json", ".", "dumps", "(", "dict", "(", "hash", "=", "pkghash", ")", ")", ")", "print", "(", "\"Push complete. %s is live:\\n%s\"", "%", "(", "package", ",", "package_url", ")", ")" ]
Push a Quilt data package to the server
[ "Push", "a", "Quilt", "data", "package", "to", "the", "server" ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L671-L766
8,229
quiltdata/quilt
compiler/quilt/tools/command.py
version_list
def version_list(package): """ List the versions of a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/version/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg ) ) for version in response.json()['versions']: print("%s: %s" % (version['version'], version['hash']))
python
def version_list(package): """ List the versions of a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/version/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg ) ) for version in response.json()['versions']: print("%s: %s" % (version['version'], version['hash']))
[ "def", "version_list", "(", "package", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "session", "=", "_get_session", "(", "team", ")", "response", "=", "session", ".", "get", "(", "\"{url}/api/version/{owner}/{pkg}/\"", ".", "format", "(", "url", "=", "get_registry_url", "(", "team", ")", ",", "owner", "=", "owner", ",", "pkg", "=", "pkg", ")", ")", "for", "version", "in", "response", ".", "json", "(", ")", "[", "'versions'", "]", ":", "print", "(", "\"%s: %s\"", "%", "(", "version", "[", "'version'", "]", ",", "version", "[", "'hash'", "]", ")", ")" ]
List the versions of a package.
[ "List", "the", "versions", "of", "a", "package", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L768-L784
8,230
quiltdata/quilt
compiler/quilt/tools/command.py
version_add
def version_add(package, version, pkghash, force=False): """ Add a new version for a given package hash. Version format needs to follow PEP 440. Versions are permanent - once created, they cannot be modified or deleted. """ team, owner, pkg = parse_package(package) session = _get_session(team) try: Version(version) except ValueError: url = "https://www.python.org/dev/peps/pep-0440/#examples-of-compliant-version-schemes" raise CommandException( "Invalid version format; see %s" % url ) if not force: answer = input("Versions cannot be modified or deleted; are you sure? (y/n) ") if answer.lower() != 'y': return session.put( "{url}/api/version/{owner}/{pkg}/{version}".format( url=get_registry_url(team), owner=owner, pkg=pkg, version=version ), data=json.dumps(dict( hash=_match_hash(package, pkghash) )) )
python
def version_add(package, version, pkghash, force=False): """ Add a new version for a given package hash. Version format needs to follow PEP 440. Versions are permanent - once created, they cannot be modified or deleted. """ team, owner, pkg = parse_package(package) session = _get_session(team) try: Version(version) except ValueError: url = "https://www.python.org/dev/peps/pep-0440/#examples-of-compliant-version-schemes" raise CommandException( "Invalid version format; see %s" % url ) if not force: answer = input("Versions cannot be modified or deleted; are you sure? (y/n) ") if answer.lower() != 'y': return session.put( "{url}/api/version/{owner}/{pkg}/{version}".format( url=get_registry_url(team), owner=owner, pkg=pkg, version=version ), data=json.dumps(dict( hash=_match_hash(package, pkghash) )) )
[ "def", "version_add", "(", "package", ",", "version", ",", "pkghash", ",", "force", "=", "False", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "session", "=", "_get_session", "(", "team", ")", "try", ":", "Version", "(", "version", ")", "except", "ValueError", ":", "url", "=", "\"https://www.python.org/dev/peps/pep-0440/#examples-of-compliant-version-schemes\"", "raise", "CommandException", "(", "\"Invalid version format; see %s\"", "%", "url", ")", "if", "not", "force", ":", "answer", "=", "input", "(", "\"Versions cannot be modified or deleted; are you sure? (y/n) \"", ")", "if", "answer", ".", "lower", "(", ")", "!=", "'y'", ":", "return", "session", ".", "put", "(", "\"{url}/api/version/{owner}/{pkg}/{version}\"", ".", "format", "(", "url", "=", "get_registry_url", "(", "team", ")", ",", "owner", "=", "owner", ",", "pkg", "=", "pkg", ",", "version", "=", "version", ")", ",", "data", "=", "json", ".", "dumps", "(", "dict", "(", "hash", "=", "_match_hash", "(", "package", ",", "pkghash", ")", ")", ")", ")" ]
Add a new version for a given package hash. Version format needs to follow PEP 440. Versions are permanent - once created, they cannot be modified or deleted.
[ "Add", "a", "new", "version", "for", "a", "given", "package", "hash", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L786-L819
8,231
quiltdata/quilt
compiler/quilt/tools/command.py
tag_list
def tag_list(package): """ List the tags of a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/tag/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg ) ) for tag in response.json()['tags']: print("%s: %s" % (tag['tag'], tag['hash']))
python
def tag_list(package): """ List the tags of a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/tag/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg ) ) for tag in response.json()['tags']: print("%s: %s" % (tag['tag'], tag['hash']))
[ "def", "tag_list", "(", "package", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "session", "=", "_get_session", "(", "team", ")", "response", "=", "session", ".", "get", "(", "\"{url}/api/tag/{owner}/{pkg}/\"", ".", "format", "(", "url", "=", "get_registry_url", "(", "team", ")", ",", "owner", "=", "owner", ",", "pkg", "=", "pkg", ")", ")", "for", "tag", "in", "response", ".", "json", "(", ")", "[", "'tags'", "]", ":", "print", "(", "\"%s: %s\"", "%", "(", "tag", "[", "'tag'", "]", ",", "tag", "[", "'hash'", "]", ")", ")" ]
List the tags of a package.
[ "List", "the", "tags", "of", "a", "package", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L821-L837
8,232
quiltdata/quilt
compiler/quilt/tools/command.py
tag_add
def tag_add(package, tag, pkghash): """ Add a new tag for a given package hash. Unlike versions, tags can have an arbitrary format, and can be modified and deleted. When a package is pushed, it gets the "latest" tag. """ team, owner, pkg = parse_package(package) session = _get_session(team) session.put( "{url}/api/tag/{owner}/{pkg}/{tag}".format( url=get_registry_url(team), owner=owner, pkg=pkg, tag=tag ), data=json.dumps(dict( hash=_match_hash(package, pkghash) )) )
python
def tag_add(package, tag, pkghash): """ Add a new tag for a given package hash. Unlike versions, tags can have an arbitrary format, and can be modified and deleted. When a package is pushed, it gets the "latest" tag. """ team, owner, pkg = parse_package(package) session = _get_session(team) session.put( "{url}/api/tag/{owner}/{pkg}/{tag}".format( url=get_registry_url(team), owner=owner, pkg=pkg, tag=tag ), data=json.dumps(dict( hash=_match_hash(package, pkghash) )) )
[ "def", "tag_add", "(", "package", ",", "tag", ",", "pkghash", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "session", "=", "_get_session", "(", "team", ")", "session", ".", "put", "(", "\"{url}/api/tag/{owner}/{pkg}/{tag}\"", ".", "format", "(", "url", "=", "get_registry_url", "(", "team", ")", ",", "owner", "=", "owner", ",", "pkg", "=", "pkg", ",", "tag", "=", "tag", ")", ",", "data", "=", "json", ".", "dumps", "(", "dict", "(", "hash", "=", "_match_hash", "(", "package", ",", "pkghash", ")", ")", ")", ")" ]
Add a new tag for a given package hash. Unlike versions, tags can have an arbitrary format, and can be modified and deleted. When a package is pushed, it gets the "latest" tag.
[ "Add", "a", "new", "tag", "for", "a", "given", "package", "hash", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L839-L861
8,233
quiltdata/quilt
compiler/quilt/tools/command.py
install_via_requirements
def install_via_requirements(requirements_str, force=False): """ Download multiple Quilt data packages via quilt.xml requirements file. """ if requirements_str[0] == '@': path = requirements_str[1:] if os.path.isfile(path): yaml_data = load_yaml(path) if 'packages' not in yaml_data.keys(): raise CommandException('Error in {filename}: missing "packages" node'.format(filename=path)) else: raise CommandException("Requirements file not found: {filename}".format(filename=path)) else: yaml_data = yaml.safe_load(requirements_str) for pkginfo in yaml_data['packages']: info = parse_package_extended(pkginfo) install(info.full_name, info.hash, info.version, info.tag, force=force)
python
def install_via_requirements(requirements_str, force=False): """ Download multiple Quilt data packages via quilt.xml requirements file. """ if requirements_str[0] == '@': path = requirements_str[1:] if os.path.isfile(path): yaml_data = load_yaml(path) if 'packages' not in yaml_data.keys(): raise CommandException('Error in {filename}: missing "packages" node'.format(filename=path)) else: raise CommandException("Requirements file not found: {filename}".format(filename=path)) else: yaml_data = yaml.safe_load(requirements_str) for pkginfo in yaml_data['packages']: info = parse_package_extended(pkginfo) install(info.full_name, info.hash, info.version, info.tag, force=force)
[ "def", "install_via_requirements", "(", "requirements_str", ",", "force", "=", "False", ")", ":", "if", "requirements_str", "[", "0", "]", "==", "'@'", ":", "path", "=", "requirements_str", "[", "1", ":", "]", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "yaml_data", "=", "load_yaml", "(", "path", ")", "if", "'packages'", "not", "in", "yaml_data", ".", "keys", "(", ")", ":", "raise", "CommandException", "(", "'Error in {filename}: missing \"packages\" node'", ".", "format", "(", "filename", "=", "path", ")", ")", "else", ":", "raise", "CommandException", "(", "\"Requirements file not found: {filename}\"", ".", "format", "(", "filename", "=", "path", ")", ")", "else", ":", "yaml_data", "=", "yaml", ".", "safe_load", "(", "requirements_str", ")", "for", "pkginfo", "in", "yaml_data", "[", "'packages'", "]", ":", "info", "=", "parse_package_extended", "(", "pkginfo", ")", "install", "(", "info", ".", "full_name", ",", "info", ".", "hash", ",", "info", ".", "version", ",", "info", ".", "tag", ",", "force", "=", "force", ")" ]
Download multiple Quilt data packages via quilt.xml requirements file.
[ "Download", "multiple", "Quilt", "data", "packages", "via", "quilt", ".", "xml", "requirements", "file", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L879-L895
8,234
quiltdata/quilt
compiler/quilt/tools/command.py
access_list
def access_list(package): """ Print list of users who can access a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) lookup_url = "{url}/api/access/{owner}/{pkg}/".format(url=get_registry_url(team), owner=owner, pkg=pkg) response = session.get(lookup_url) data = response.json() users = data['users'] print('\n'.join(users))
python
def access_list(package): """ Print list of users who can access a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) lookup_url = "{url}/api/access/{owner}/{pkg}/".format(url=get_registry_url(team), owner=owner, pkg=pkg) response = session.get(lookup_url) data = response.json() users = data['users'] print('\n'.join(users))
[ "def", "access_list", "(", "package", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "session", "=", "_get_session", "(", "team", ")", "lookup_url", "=", "\"{url}/api/access/{owner}/{pkg}/\"", ".", "format", "(", "url", "=", "get_registry_url", "(", "team", ")", ",", "owner", "=", "owner", ",", "pkg", "=", "pkg", ")", "response", "=", "session", ".", "get", "(", "lookup_url", ")", "data", "=", "response", ".", "json", "(", ")", "users", "=", "data", "[", "'users'", "]", "print", "(", "'\\n'", ".", "join", "(", "users", ")", ")" ]
Print list of users who can access a package.
[ "Print", "list", "of", "users", "who", "can", "access", "a", "package", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L1061-L1074
8,235
quiltdata/quilt
compiler/quilt/tools/command.py
delete
def delete(package): """ Delete a package from the server. Irreversibly deletes the package along with its history, tags, versions, etc. """ team, owner, pkg = parse_package(package) answer = input( "Are you sure you want to delete this package and its entire history? " "Type '%s' to confirm: " % package ) if answer != package: print("Not deleting.") return 1 session = _get_session(team) session.delete("%s/api/package/%s/%s/" % (get_registry_url(team), owner, pkg)) print("Deleted.")
python
def delete(package): """ Delete a package from the server. Irreversibly deletes the package along with its history, tags, versions, etc. """ team, owner, pkg = parse_package(package) answer = input( "Are you sure you want to delete this package and its entire history? " "Type '%s' to confirm: " % package ) if answer != package: print("Not deleting.") return 1 session = _get_session(team) session.delete("%s/api/package/%s/%s/" % (get_registry_url(team), owner, pkg)) print("Deleted.")
[ "def", "delete", "(", "package", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "answer", "=", "input", "(", "\"Are you sure you want to delete this package and its entire history? \"", "\"Type '%s' to confirm: \"", "%", "package", ")", "if", "answer", "!=", "package", ":", "print", "(", "\"Not deleting.\"", ")", "return", "1", "session", "=", "_get_session", "(", "team", ")", "session", ".", "delete", "(", "\"%s/api/package/%s/%s/\"", "%", "(", "get_registry_url", "(", "team", ")", ",", "owner", ",", "pkg", ")", ")", "print", "(", "\"Deleted.\"", ")" ]
Delete a package from the server. Irreversibly deletes the package along with its history, tags, versions, etc.
[ "Delete", "a", "package", "from", "the", "server", "." ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L1096-L1116
8,236
quiltdata/quilt
compiler/quilt/tools/command.py
search
def search(query, team=None): """ Search for packages """ if team is None: team = _find_logged_in_team() if team is not None: session = _get_session(team) response = session.get("%s/api/search/" % get_registry_url(team), params=dict(q=query)) print("* Packages in team %s" % team) packages = response.json()['packages'] for pkg in packages: print(("%s:" % team) + ("%(owner)s/%(name)s" % pkg)) if len(packages) == 0: print("(No results)") print("* Packages in public cloud") public_session = _get_session(None) response = public_session.get("%s/api/search/" % get_registry_url(None), params=dict(q=query)) packages = response.json()['packages'] for pkg in packages: print("%(owner)s/%(name)s" % pkg) if len(packages) == 0: print("(No results)")
python
def search(query, team=None): """ Search for packages """ if team is None: team = _find_logged_in_team() if team is not None: session = _get_session(team) response = session.get("%s/api/search/" % get_registry_url(team), params=dict(q=query)) print("* Packages in team %s" % team) packages = response.json()['packages'] for pkg in packages: print(("%s:" % team) + ("%(owner)s/%(name)s" % pkg)) if len(packages) == 0: print("(No results)") print("* Packages in public cloud") public_session = _get_session(None) response = public_session.get("%s/api/search/" % get_registry_url(None), params=dict(q=query)) packages = response.json()['packages'] for pkg in packages: print("%(owner)s/%(name)s" % pkg) if len(packages) == 0: print("(No results)")
[ "def", "search", "(", "query", ",", "team", "=", "None", ")", ":", "if", "team", "is", "None", ":", "team", "=", "_find_logged_in_team", "(", ")", "if", "team", "is", "not", "None", ":", "session", "=", "_get_session", "(", "team", ")", "response", "=", "session", ".", "get", "(", "\"%s/api/search/\"", "%", "get_registry_url", "(", "team", ")", ",", "params", "=", "dict", "(", "q", "=", "query", ")", ")", "print", "(", "\"* Packages in team %s\"", "%", "team", ")", "packages", "=", "response", ".", "json", "(", ")", "[", "'packages'", "]", "for", "pkg", "in", "packages", ":", "print", "(", "(", "\"%s:\"", "%", "team", ")", "+", "(", "\"%(owner)s/%(name)s\"", "%", "pkg", ")", ")", "if", "len", "(", "packages", ")", "==", "0", ":", "print", "(", "\"(No results)\"", ")", "print", "(", "\"* Packages in public cloud\"", ")", "public_session", "=", "_get_session", "(", "None", ")", "response", "=", "public_session", ".", "get", "(", "\"%s/api/search/\"", "%", "get_registry_url", "(", "None", ")", ",", "params", "=", "dict", "(", "q", "=", "query", ")", ")", "packages", "=", "response", ".", "json", "(", ")", "[", "'packages'", "]", "for", "pkg", "in", "packages", ":", "print", "(", "\"%(owner)s/%(name)s\"", "%", "pkg", ")", "if", "len", "(", "packages", ")", "==", "0", ":", "print", "(", "\"(No results)\"", ")" ]
Search for packages
[ "Search", "for", "packages" ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L1118-L1142
8,237
quiltdata/quilt
compiler/quilt/tools/command.py
ls
def ls(): # pylint:disable=C0103 """ List all installed Quilt data packages """ for pkg_dir in PackageStore.find_store_dirs(): print("%s" % pkg_dir) packages = PackageStore(pkg_dir).ls_packages() for package, tag, pkghash in sorted(packages): print("{0:30} {1:20} {2}".format(package, tag, pkghash))
python
def ls(): # pylint:disable=C0103 """ List all installed Quilt data packages """ for pkg_dir in PackageStore.find_store_dirs(): print("%s" % pkg_dir) packages = PackageStore(pkg_dir).ls_packages() for package, tag, pkghash in sorted(packages): print("{0:30} {1:20} {2}".format(package, tag, pkghash))
[ "def", "ls", "(", ")", ":", "# pylint:disable=C0103", "for", "pkg_dir", "in", "PackageStore", ".", "find_store_dirs", "(", ")", ":", "print", "(", "\"%s\"", "%", "pkg_dir", ")", "packages", "=", "PackageStore", "(", "pkg_dir", ")", ".", "ls_packages", "(", ")", "for", "package", ",", "tag", ",", "pkghash", "in", "sorted", "(", "packages", ")", ":", "print", "(", "\"{0:30} {1:20} {2}\"", ".", "format", "(", "package", ",", "tag", ",", "pkghash", ")", ")" ]
List all installed Quilt data packages
[ "List", "all", "installed", "Quilt", "data", "packages" ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L1144-L1152
8,238
quiltdata/quilt
compiler/quilt/tools/command.py
inspect
def inspect(package): """ Inspect package details """ team, owner, pkg = parse_package(package) store, pkgroot = PackageStore.find_package(team, owner, pkg) if pkgroot is None: raise CommandException("Package {package} not found.".format(package=package)) def _print_children(children, prefix, path): for idx, (name, child) in enumerate(children): if idx == len(children) - 1: new_prefix = u"└─" new_child_prefix = u" " else: new_prefix = u"├─" new_child_prefix = u"│ " _print_node(child, prefix + new_prefix, prefix + new_child_prefix, name, path) def _print_node(node, prefix, child_prefix, name, path): name_prefix = u"─ " if isinstance(node, GroupNode): children = list(node.children.items()) if children: name_prefix = u"┬ " print(prefix + name_prefix + name) _print_children(children, child_prefix, path + name) elif node.metadata['q_target'] == TargetType.PANDAS.value: df = store.load_dataframe(node.hashes) assert isinstance(df, pd.DataFrame) types = ", ".join("%r: %s" % (name, dtype) for name, dtype in df.dtypes.items()) if len(types) > 64: types = types[:63] + u"…" info = "shape %s, types %s" % (df.shape, types) print(prefix + name_prefix + name + ": " + info) else: print(prefix + name_prefix + name) print(store.package_path(team, owner, pkg)) _print_children(children=pkgroot.children.items(), prefix='', path='')
python
def inspect(package): """ Inspect package details """ team, owner, pkg = parse_package(package) store, pkgroot = PackageStore.find_package(team, owner, pkg) if pkgroot is None: raise CommandException("Package {package} not found.".format(package=package)) def _print_children(children, prefix, path): for idx, (name, child) in enumerate(children): if idx == len(children) - 1: new_prefix = u"└─" new_child_prefix = u" " else: new_prefix = u"├─" new_child_prefix = u"│ " _print_node(child, prefix + new_prefix, prefix + new_child_prefix, name, path) def _print_node(node, prefix, child_prefix, name, path): name_prefix = u"─ " if isinstance(node, GroupNode): children = list(node.children.items()) if children: name_prefix = u"┬ " print(prefix + name_prefix + name) _print_children(children, child_prefix, path + name) elif node.metadata['q_target'] == TargetType.PANDAS.value: df = store.load_dataframe(node.hashes) assert isinstance(df, pd.DataFrame) types = ", ".join("%r: %s" % (name, dtype) for name, dtype in df.dtypes.items()) if len(types) > 64: types = types[:63] + u"…" info = "shape %s, types %s" % (df.shape, types) print(prefix + name_prefix + name + ": " + info) else: print(prefix + name_prefix + name) print(store.package_path(team, owner, pkg)) _print_children(children=pkgroot.children.items(), prefix='', path='')
[ "def", "inspect", "(", "package", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "store", ",", "pkgroot", "=", "PackageStore", ".", "find_package", "(", "team", ",", "owner", ",", "pkg", ")", "if", "pkgroot", "is", "None", ":", "raise", "CommandException", "(", "\"Package {package} not found.\"", ".", "format", "(", "package", "=", "package", ")", ")", "def", "_print_children", "(", "children", ",", "prefix", ",", "path", ")", ":", "for", "idx", ",", "(", "name", ",", "child", ")", "in", "enumerate", "(", "children", ")", ":", "if", "idx", "==", "len", "(", "children", ")", "-", "1", ":", "new_prefix", "=", "u\"└─\"", "new_child_prefix", "=", "u\" \"", "else", ":", "new_prefix", "=", "u\"├─\"", "new_child_prefix", "=", "u\"│ \"", "_print_node", "(", "child", ",", "prefix", "+", "new_prefix", ",", "prefix", "+", "new_child_prefix", ",", "name", ",", "path", ")", "def", "_print_node", "(", "node", ",", "prefix", ",", "child_prefix", ",", "name", ",", "path", ")", ":", "name_prefix", "=", "u\"─ \"", "if", "isinstance", "(", "node", ",", "GroupNode", ")", ":", "children", "=", "list", "(", "node", ".", "children", ".", "items", "(", ")", ")", "if", "children", ":", "name_prefix", "=", "u\"┬ \"", "print", "(", "prefix", "+", "name_prefix", "+", "name", ")", "_print_children", "(", "children", ",", "child_prefix", ",", "path", "+", "name", ")", "elif", "node", ".", "metadata", "[", "'q_target'", "]", "==", "TargetType", ".", "PANDAS", ".", "value", ":", "df", "=", "store", ".", "load_dataframe", "(", "node", ".", "hashes", ")", "assert", "isinstance", "(", "df", ",", "pd", ".", "DataFrame", ")", "types", "=", "\", \"", ".", "join", "(", "\"%r: %s\"", "%", "(", "name", ",", "dtype", ")", "for", "name", ",", "dtype", "in", "df", ".", "dtypes", ".", "items", "(", ")", ")", "if", "len", "(", "types", ")", ">", "64", ":", "types", "=", "types", "[", ":", "63", "]", "+", "u\"…\"", "info", "=", "\"shape %s, types %s\"", "%", "(", "df", ".", "shape", ",", "types", ")", "print", "(", "prefix", "+", "name_prefix", "+", "name", "+", "\": \"", "+", "info", ")", "else", ":", "print", "(", "prefix", "+", "name_prefix", "+", "name", ")", "print", "(", "store", ".", "package_path", "(", "team", ",", "owner", ",", "pkg", ")", ")", "_print_children", "(", "children", "=", "pkgroot", ".", "children", ".", "items", "(", ")", ",", "prefix", "=", "''", ",", "path", "=", "''", ")" ]
Inspect package details
[ "Inspect", "package", "details" ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L1154-L1194
8,239
quiltdata/quilt
compiler/quilt/tools/command.py
load
def load(pkginfo, hash=None): """ functional interface to "from quilt.data.USER import PKG" """ node, pkgroot, info = _load(pkginfo, hash) for subnode_name in info.subpath: node = node[subnode_name] return node
python
def load(pkginfo, hash=None): """ functional interface to "from quilt.data.USER import PKG" """ node, pkgroot, info = _load(pkginfo, hash) for subnode_name in info.subpath: node = node[subnode_name] return node
[ "def", "load", "(", "pkginfo", ",", "hash", "=", "None", ")", ":", "node", ",", "pkgroot", ",", "info", "=", "_load", "(", "pkginfo", ",", "hash", ")", "for", "subnode_name", "in", "info", ".", "subpath", ":", "node", "=", "node", "[", "subnode_name", "]", "return", "node" ]
functional interface to "from quilt.data.USER import PKG"
[ "functional", "interface", "to", "from", "quilt", ".", "data", ".", "USER", "import", "PKG" ]
651853e7e89a8af86e0ff26167e752efa5878c12
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/command.py#L1351-L1359
8,240
CalebBell/fluids
fluids/core.py
c_ideal_gas
def c_ideal_gas(T, k, MW): r'''Calculates speed of sound `c` in an ideal gas at temperature T. .. math:: c = \sqrt{kR_{specific}T} Parameters ---------- T : float Temperature of fluid, [K] k : float Isentropic exponent of fluid, [-] MW : float Molecular weight of fluid, [g/mol] Returns ------- c : float Speed of sound in fluid, [m/s] Notes ----- Used in compressible flow calculations. Note that the gas constant used is the specific gas constant: .. math:: R_{specific} = R\frac{1000}{MW} Examples -------- >>> c_ideal_gas(T=303, k=1.4, MW=28.96) 348.9820953185441 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' Rspecific = R*1000./MW return (k*Rspecific*T)**0.5
python
def c_ideal_gas(T, k, MW): r'''Calculates speed of sound `c` in an ideal gas at temperature T. .. math:: c = \sqrt{kR_{specific}T} Parameters ---------- T : float Temperature of fluid, [K] k : float Isentropic exponent of fluid, [-] MW : float Molecular weight of fluid, [g/mol] Returns ------- c : float Speed of sound in fluid, [m/s] Notes ----- Used in compressible flow calculations. Note that the gas constant used is the specific gas constant: .. math:: R_{specific} = R\frac{1000}{MW} Examples -------- >>> c_ideal_gas(T=303, k=1.4, MW=28.96) 348.9820953185441 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' Rspecific = R*1000./MW return (k*Rspecific*T)**0.5
[ "def", "c_ideal_gas", "(", "T", ",", "k", ",", "MW", ")", ":", "Rspecific", "=", "R", "*", "1000.", "/", "MW", "return", "(", "k", "*", "Rspecific", "*", "T", ")", "**", "0.5" ]
r'''Calculates speed of sound `c` in an ideal gas at temperature T. .. math:: c = \sqrt{kR_{specific}T} Parameters ---------- T : float Temperature of fluid, [K] k : float Isentropic exponent of fluid, [-] MW : float Molecular weight of fluid, [g/mol] Returns ------- c : float Speed of sound in fluid, [m/s] Notes ----- Used in compressible flow calculations. Note that the gas constant used is the specific gas constant: .. math:: R_{specific} = R\frac{1000}{MW} Examples -------- >>> c_ideal_gas(T=303, k=1.4, MW=28.96) 348.9820953185441 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006.
[ "r", "Calculates", "speed", "of", "sound", "c", "in", "an", "ideal", "gas", "at", "temperature", "T", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L82-L123
8,241
CalebBell/fluids
fluids/core.py
Reynolds
def Reynolds(V, D, rho=None, mu=None, nu=None): r'''Calculates Reynolds number or `Re` for a fluid with the given properties for the specified velocity and diameter. .. math:: Re = \frac{D \cdot V}{\nu} = \frac{\rho V D}{\mu} Inputs either of any of the following sets: * V, D, density `rho` and kinematic viscosity `mu` * V, D, and dynamic viscosity `nu` Parameters ---------- V : float Velocity [m/s] D : float Diameter [m] rho : float, optional Density, [kg/m^3] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] Returns ------- Re : float Reynolds number [] Notes ----- .. math:: Re = \frac{\text{Momentum}}{\text{Viscosity}} An error is raised if none of the required input sets are provided. Examples -------- >>> Reynolds(2.5, 0.25, 1.1613, 1.9E-5) 38200.65789473684 >>> Reynolds(2.5, 0.25, nu=1.636e-05) 38202.93398533008 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if rho and mu: nu = mu/rho elif not nu: raise Exception('Either density and viscosity, or dynamic viscosity, \ is needed') return V*D/nu
python
def Reynolds(V, D, rho=None, mu=None, nu=None): r'''Calculates Reynolds number or `Re` for a fluid with the given properties for the specified velocity and diameter. .. math:: Re = \frac{D \cdot V}{\nu} = \frac{\rho V D}{\mu} Inputs either of any of the following sets: * V, D, density `rho` and kinematic viscosity `mu` * V, D, and dynamic viscosity `nu` Parameters ---------- V : float Velocity [m/s] D : float Diameter [m] rho : float, optional Density, [kg/m^3] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] Returns ------- Re : float Reynolds number [] Notes ----- .. math:: Re = \frac{\text{Momentum}}{\text{Viscosity}} An error is raised if none of the required input sets are provided. Examples -------- >>> Reynolds(2.5, 0.25, 1.1613, 1.9E-5) 38200.65789473684 >>> Reynolds(2.5, 0.25, nu=1.636e-05) 38202.93398533008 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if rho and mu: nu = mu/rho elif not nu: raise Exception('Either density and viscosity, or dynamic viscosity, \ is needed') return V*D/nu
[ "def", "Reynolds", "(", "V", ",", "D", ",", "rho", "=", "None", ",", "mu", "=", "None", ",", "nu", "=", "None", ")", ":", "if", "rho", "and", "mu", ":", "nu", "=", "mu", "/", "rho", "elif", "not", "nu", ":", "raise", "Exception", "(", "'Either density and viscosity, or dynamic viscosity, \\\n is needed'", ")", "return", "V", "*", "D", "/", "nu" ]
r'''Calculates Reynolds number or `Re` for a fluid with the given properties for the specified velocity and diameter. .. math:: Re = \frac{D \cdot V}{\nu} = \frac{\rho V D}{\mu} Inputs either of any of the following sets: * V, D, density `rho` and kinematic viscosity `mu` * V, D, and dynamic viscosity `nu` Parameters ---------- V : float Velocity [m/s] D : float Diameter [m] rho : float, optional Density, [kg/m^3] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] Returns ------- Re : float Reynolds number [] Notes ----- .. math:: Re = \frac{\text{Momentum}}{\text{Viscosity}} An error is raised if none of the required input sets are provided. Examples -------- >>> Reynolds(2.5, 0.25, 1.1613, 1.9E-5) 38200.65789473684 >>> Reynolds(2.5, 0.25, nu=1.636e-05) 38202.93398533008 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006.
[ "r", "Calculates", "Reynolds", "number", "or", "Re", "for", "a", "fluid", "with", "the", "given", "properties", "for", "the", "specified", "velocity", "and", "diameter", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L128-L184
8,242
CalebBell/fluids
fluids/core.py
Peclet_heat
def Peclet_heat(V, L, rho=None, Cp=None, k=None, alpha=None): r'''Calculates heat transfer Peclet number or `Pe` for a specified velocity `V`, characteristic length `L`, and specified properties for the given fluid. .. math:: Pe = \frac{VL\rho C_p}{k} = \frac{LV}{\alpha} Inputs either of any of the following sets: * V, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k` * V, L, and thermal diffusivity `alpha` Parameters ---------- V : float Velocity [m/s] L : float Characteristic length [m] rho : float, optional Density, [kg/m^3] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] alpha : float, optional Thermal diffusivity, [m^2/s] Returns ------- Pe : float Peclet number (heat) [] Notes ----- .. math:: Pe = \frac{\text{Bulk heat transfer}}{\text{Conduction heat transfer}} An error is raised if none of the required input sets are provided. Examples -------- >>> Peclet_heat(1.5, 2, 1000., 4000., 0.6) 20000000.0 >>> Peclet_heat(1.5, 2, alpha=1E-7) 30000000.0 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if rho and Cp and k: alpha = k/(rho*Cp) elif not alpha: raise Exception('Either heat capacity and thermal conductivity and\ density, or thermal diffusivity is needed') return V*L/alpha
python
def Peclet_heat(V, L, rho=None, Cp=None, k=None, alpha=None): r'''Calculates heat transfer Peclet number or `Pe` for a specified velocity `V`, characteristic length `L`, and specified properties for the given fluid. .. math:: Pe = \frac{VL\rho C_p}{k} = \frac{LV}{\alpha} Inputs either of any of the following sets: * V, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k` * V, L, and thermal diffusivity `alpha` Parameters ---------- V : float Velocity [m/s] L : float Characteristic length [m] rho : float, optional Density, [kg/m^3] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] alpha : float, optional Thermal diffusivity, [m^2/s] Returns ------- Pe : float Peclet number (heat) [] Notes ----- .. math:: Pe = \frac{\text{Bulk heat transfer}}{\text{Conduction heat transfer}} An error is raised if none of the required input sets are provided. Examples -------- >>> Peclet_heat(1.5, 2, 1000., 4000., 0.6) 20000000.0 >>> Peclet_heat(1.5, 2, alpha=1E-7) 30000000.0 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if rho and Cp and k: alpha = k/(rho*Cp) elif not alpha: raise Exception('Either heat capacity and thermal conductivity and\ density, or thermal diffusivity is needed') return V*L/alpha
[ "def", "Peclet_heat", "(", "V", ",", "L", ",", "rho", "=", "None", ",", "Cp", "=", "None", ",", "k", "=", "None", ",", "alpha", "=", "None", ")", ":", "if", "rho", "and", "Cp", "and", "k", ":", "alpha", "=", "k", "/", "(", "rho", "*", "Cp", ")", "elif", "not", "alpha", ":", "raise", "Exception", "(", "'Either heat capacity and thermal conductivity and\\\n density, or thermal diffusivity is needed'", ")", "return", "V", "*", "L", "/", "alpha" ]
r'''Calculates heat transfer Peclet number or `Pe` for a specified velocity `V`, characteristic length `L`, and specified properties for the given fluid. .. math:: Pe = \frac{VL\rho C_p}{k} = \frac{LV}{\alpha} Inputs either of any of the following sets: * V, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k` * V, L, and thermal diffusivity `alpha` Parameters ---------- V : float Velocity [m/s] L : float Characteristic length [m] rho : float, optional Density, [kg/m^3] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] alpha : float, optional Thermal diffusivity, [m^2/s] Returns ------- Pe : float Peclet number (heat) [] Notes ----- .. math:: Pe = \frac{\text{Bulk heat transfer}}{\text{Conduction heat transfer}} An error is raised if none of the required input sets are provided. Examples -------- >>> Peclet_heat(1.5, 2, 1000., 4000., 0.6) 20000000.0 >>> Peclet_heat(1.5, 2, alpha=1E-7) 30000000.0 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006.
[ "r", "Calculates", "heat", "transfer", "Peclet", "number", "or", "Pe", "for", "a", "specified", "velocity", "V", "characteristic", "length", "L", "and", "specified", "properties", "for", "the", "given", "fluid", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L187-L246
8,243
CalebBell/fluids
fluids/core.py
Fourier_heat
def Fourier_heat(t, L, rho=None, Cp=None, k=None, alpha=None): r'''Calculates heat transfer Fourier number or `Fo` for a specified time `t`, characteristic length `L`, and specified properties for the given fluid. .. math:: Fo = \frac{k t}{C_p \rho L^2} = \frac{\alpha t}{L^2} Inputs either of any of the following sets: * t, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k` * t, L, and thermal diffusivity `alpha` Parameters ---------- t : float time [s] L : float Characteristic length [m] rho : float, optional Density, [kg/m^3] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] alpha : float, optional Thermal diffusivity, [m^2/s] Returns ------- Fo : float Fourier number (heat) [] Notes ----- .. math:: Fo = \frac{\text{Heat conduction rate}} {\text{Rate of thermal energy storage in a solid}} An error is raised if none of the required input sets are provided. Examples -------- >>> Fourier_heat(t=1.5, L=2, rho=1000., Cp=4000., k=0.6) 5.625e-08 >>> Fourier_heat(1.5, 2, alpha=1E-7) 3.75e-08 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if rho and Cp and k: alpha = k/(rho*Cp) elif not alpha: raise Exception('Either heat capacity and thermal conductivity and \ density, or thermal diffusivity is needed') return t*alpha/L**2
python
def Fourier_heat(t, L, rho=None, Cp=None, k=None, alpha=None): r'''Calculates heat transfer Fourier number or `Fo` for a specified time `t`, characteristic length `L`, and specified properties for the given fluid. .. math:: Fo = \frac{k t}{C_p \rho L^2} = \frac{\alpha t}{L^2} Inputs either of any of the following sets: * t, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k` * t, L, and thermal diffusivity `alpha` Parameters ---------- t : float time [s] L : float Characteristic length [m] rho : float, optional Density, [kg/m^3] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] alpha : float, optional Thermal diffusivity, [m^2/s] Returns ------- Fo : float Fourier number (heat) [] Notes ----- .. math:: Fo = \frac{\text{Heat conduction rate}} {\text{Rate of thermal energy storage in a solid}} An error is raised if none of the required input sets are provided. Examples -------- >>> Fourier_heat(t=1.5, L=2, rho=1000., Cp=4000., k=0.6) 5.625e-08 >>> Fourier_heat(1.5, 2, alpha=1E-7) 3.75e-08 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if rho and Cp and k: alpha = k/(rho*Cp) elif not alpha: raise Exception('Either heat capacity and thermal conductivity and \ density, or thermal diffusivity is needed') return t*alpha/L**2
[ "def", "Fourier_heat", "(", "t", ",", "L", ",", "rho", "=", "None", ",", "Cp", "=", "None", ",", "k", "=", "None", ",", "alpha", "=", "None", ")", ":", "if", "rho", "and", "Cp", "and", "k", ":", "alpha", "=", "k", "/", "(", "rho", "*", "Cp", ")", "elif", "not", "alpha", ":", "raise", "Exception", "(", "'Either heat capacity and thermal conductivity and \\\ndensity, or thermal diffusivity is needed'", ")", "return", "t", "*", "alpha", "/", "L", "**", "2" ]
r'''Calculates heat transfer Fourier number or `Fo` for a specified time `t`, characteristic length `L`, and specified properties for the given fluid. .. math:: Fo = \frac{k t}{C_p \rho L^2} = \frac{\alpha t}{L^2} Inputs either of any of the following sets: * t, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k` * t, L, and thermal diffusivity `alpha` Parameters ---------- t : float time [s] L : float Characteristic length [m] rho : float, optional Density, [kg/m^3] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] alpha : float, optional Thermal diffusivity, [m^2/s] Returns ------- Fo : float Fourier number (heat) [] Notes ----- .. math:: Fo = \frac{\text{Heat conduction rate}} {\text{Rate of thermal energy storage in a solid}} An error is raised if none of the required input sets are provided. Examples -------- >>> Fourier_heat(t=1.5, L=2, rho=1000., Cp=4000., k=0.6) 5.625e-08 >>> Fourier_heat(1.5, 2, alpha=1E-7) 3.75e-08 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006.
[ "r", "Calculates", "heat", "transfer", "Fourier", "number", "or", "Fo", "for", "a", "specified", "time", "t", "characteristic", "length", "L", "and", "specified", "properties", "for", "the", "given", "fluid", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L288-L348
8,244
CalebBell/fluids
fluids/core.py
Graetz_heat
def Graetz_heat(V, D, x, rho=None, Cp=None, k=None, alpha=None): r'''Calculates Graetz number or `Gz` for a specified velocity `V`, diameter `D`, axial distance `x`, and specified properties for the given fluid. .. math:: Gz = \frac{VD^2\cdot C_p \rho}{x\cdot k} = \frac{VD^2}{x \alpha} Inputs either of any of the following sets: * V, D, x, density `rho`, heat capacity `Cp`, and thermal conductivity `k` * V, D, x, and thermal diffusivity `alpha` Parameters ---------- V : float Velocity, [m/s] D : float Diameter [m] x : float Axial distance [m] rho : float, optional Density, [kg/m^3] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] alpha : float, optional Thermal diffusivity, [m^2/s] Returns ------- Gz : float Graetz number [] Notes ----- .. math:: Gz = \frac{\text{Time for radial heat diffusion in a fluid by conduction}} {\text{Time taken by fluid to reach distance x}} .. math:: Gz = \frac{D}{x}RePr An error is raised if none of the required input sets are provided. Examples -------- >>> Graetz_heat(1.5, 0.25, 5, 800., 2200., 0.6) 55000.0 >>> Graetz_heat(1.5, 0.25, 5, alpha=1E-7) 187500.0 References ---------- .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011. ''' if rho and Cp and k: alpha = k/(rho*Cp) elif not alpha: raise Exception('Either heat capacity and thermal conductivity and\ density, or thermal diffusivity is needed') return V*D**2/(x*alpha)
python
def Graetz_heat(V, D, x, rho=None, Cp=None, k=None, alpha=None): r'''Calculates Graetz number or `Gz` for a specified velocity `V`, diameter `D`, axial distance `x`, and specified properties for the given fluid. .. math:: Gz = \frac{VD^2\cdot C_p \rho}{x\cdot k} = \frac{VD^2}{x \alpha} Inputs either of any of the following sets: * V, D, x, density `rho`, heat capacity `Cp`, and thermal conductivity `k` * V, D, x, and thermal diffusivity `alpha` Parameters ---------- V : float Velocity, [m/s] D : float Diameter [m] x : float Axial distance [m] rho : float, optional Density, [kg/m^3] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] alpha : float, optional Thermal diffusivity, [m^2/s] Returns ------- Gz : float Graetz number [] Notes ----- .. math:: Gz = \frac{\text{Time for radial heat diffusion in a fluid by conduction}} {\text{Time taken by fluid to reach distance x}} .. math:: Gz = \frac{D}{x}RePr An error is raised if none of the required input sets are provided. Examples -------- >>> Graetz_heat(1.5, 0.25, 5, 800., 2200., 0.6) 55000.0 >>> Graetz_heat(1.5, 0.25, 5, alpha=1E-7) 187500.0 References ---------- .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011. ''' if rho and Cp and k: alpha = k/(rho*Cp) elif not alpha: raise Exception('Either heat capacity and thermal conductivity and\ density, or thermal diffusivity is needed') return V*D**2/(x*alpha)
[ "def", "Graetz_heat", "(", "V", ",", "D", ",", "x", ",", "rho", "=", "None", ",", "Cp", "=", "None", ",", "k", "=", "None", ",", "alpha", "=", "None", ")", ":", "if", "rho", "and", "Cp", "and", "k", ":", "alpha", "=", "k", "/", "(", "rho", "*", "Cp", ")", "elif", "not", "alpha", ":", "raise", "Exception", "(", "'Either heat capacity and thermal conductivity and\\\n density, or thermal diffusivity is needed'", ")", "return", "V", "*", "D", "**", "2", "/", "(", "x", "*", "alpha", ")" ]
r'''Calculates Graetz number or `Gz` for a specified velocity `V`, diameter `D`, axial distance `x`, and specified properties for the given fluid. .. math:: Gz = \frac{VD^2\cdot C_p \rho}{x\cdot k} = \frac{VD^2}{x \alpha} Inputs either of any of the following sets: * V, D, x, density `rho`, heat capacity `Cp`, and thermal conductivity `k` * V, D, x, and thermal diffusivity `alpha` Parameters ---------- V : float Velocity, [m/s] D : float Diameter [m] x : float Axial distance [m] rho : float, optional Density, [kg/m^3] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] alpha : float, optional Thermal diffusivity, [m^2/s] Returns ------- Gz : float Graetz number [] Notes ----- .. math:: Gz = \frac{\text{Time for radial heat diffusion in a fluid by conduction}} {\text{Time taken by fluid to reach distance x}} .. math:: Gz = \frac{D}{x}RePr An error is raised if none of the required input sets are provided. Examples -------- >>> Graetz_heat(1.5, 0.25, 5, 800., 2200., 0.6) 55000.0 >>> Graetz_heat(1.5, 0.25, 5, alpha=1E-7) 187500.0 References ---------- .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ: Wiley, 2011.
[ "r", "Calculates", "Graetz", "number", "or", "Gz", "for", "a", "specified", "velocity", "V", "diameter", "D", "axial", "distance", "x", "and", "specified", "properties", "for", "the", "given", "fluid", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L390-L454
8,245
CalebBell/fluids
fluids/core.py
Schmidt
def Schmidt(D, mu=None, nu=None, rho=None): r'''Calculates Schmidt number or `Sc` for a fluid with the given parameters. .. math:: Sc = \frac{\mu}{D\rho} = \frac{\nu}{D} Inputs can be any of the following sets: * Diffusivity, dynamic viscosity, and density * Diffusivity and kinematic viscosity Parameters ---------- D : float Diffusivity of a species, [m^2/s] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] rho : float, optional Density, [kg/m^3] Returns ------- Sc : float Schmidt number [] Notes ----- .. math:: Sc =\frac{\text{kinematic viscosity}}{\text{molecular diffusivity}} = \frac{\text{viscous diffusivity}}{\text{species diffusivity}} An error is raised if none of the required input sets are provided. Examples -------- >>> Schmidt(D=2E-6, mu=4.61E-6, rho=800) 0.00288125 >>> Schmidt(D=1E-9, nu=6E-7) 599.9999999999999 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if rho and mu: return mu/(rho*D) elif nu: return nu/D else: raise Exception('Insufficient information provided for Schmidt number calculation')
python
def Schmidt(D, mu=None, nu=None, rho=None): r'''Calculates Schmidt number or `Sc` for a fluid with the given parameters. .. math:: Sc = \frac{\mu}{D\rho} = \frac{\nu}{D} Inputs can be any of the following sets: * Diffusivity, dynamic viscosity, and density * Diffusivity and kinematic viscosity Parameters ---------- D : float Diffusivity of a species, [m^2/s] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] rho : float, optional Density, [kg/m^3] Returns ------- Sc : float Schmidt number [] Notes ----- .. math:: Sc =\frac{\text{kinematic viscosity}}{\text{molecular diffusivity}} = \frac{\text{viscous diffusivity}}{\text{species diffusivity}} An error is raised if none of the required input sets are provided. Examples -------- >>> Schmidt(D=2E-6, mu=4.61E-6, rho=800) 0.00288125 >>> Schmidt(D=1E-9, nu=6E-7) 599.9999999999999 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if rho and mu: return mu/(rho*D) elif nu: return nu/D else: raise Exception('Insufficient information provided for Schmidt number calculation')
[ "def", "Schmidt", "(", "D", ",", "mu", "=", "None", ",", "nu", "=", "None", ",", "rho", "=", "None", ")", ":", "if", "rho", "and", "mu", ":", "return", "mu", "/", "(", "rho", "*", "D", ")", "elif", "nu", ":", "return", "nu", "/", "D", "else", ":", "raise", "Exception", "(", "'Insufficient information provided for Schmidt number calculation'", ")" ]
r'''Calculates Schmidt number or `Sc` for a fluid with the given parameters. .. math:: Sc = \frac{\mu}{D\rho} = \frac{\nu}{D} Inputs can be any of the following sets: * Diffusivity, dynamic viscosity, and density * Diffusivity and kinematic viscosity Parameters ---------- D : float Diffusivity of a species, [m^2/s] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] rho : float, optional Density, [kg/m^3] Returns ------- Sc : float Schmidt number [] Notes ----- .. math:: Sc =\frac{\text{kinematic viscosity}}{\text{molecular diffusivity}} = \frac{\text{viscous diffusivity}}{\text{species diffusivity}} An error is raised if none of the required input sets are provided. Examples -------- >>> Schmidt(D=2E-6, mu=4.61E-6, rho=800) 0.00288125 >>> Schmidt(D=1E-9, nu=6E-7) 599.9999999999999 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006.
[ "r", "Calculates", "Schmidt", "number", "or", "Sc", "for", "a", "fluid", "with", "the", "given", "parameters", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L457-L512
8,246
CalebBell/fluids
fluids/core.py
Lewis
def Lewis(D=None, alpha=None, Cp=None, k=None, rho=None): r'''Calculates Lewis number or `Le` for a fluid with the given parameters. .. math:: Le = \frac{k}{\rho C_p D} = \frac{\alpha}{D} Inputs can be either of the following sets: * Diffusivity and Thermal diffusivity * Diffusivity, heat capacity, thermal conductivity, and density Parameters ---------- D : float Diffusivity of a species, [m^2/s] alpha : float, optional Thermal diffusivity, [m^2/s] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] rho : float, optional Density, [kg/m^3] Returns ------- Le : float Lewis number [] Notes ----- .. math:: Le=\frac{\text{Thermal diffusivity}}{\text{Mass diffusivity}} = \frac{Sc}{Pr} An error is raised if none of the required input sets are provided. Examples -------- >>> Lewis(D=22.6E-6, alpha=19.1E-6) 0.8451327433628318 >>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200) 0.00502815768302494 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition. Berlin; New York:: Springer, 2010. ''' if k and Cp and rho: alpha = k/(rho*Cp) elif alpha: pass else: raise Exception('Insufficient information provided for Le calculation') return alpha/D
python
def Lewis(D=None, alpha=None, Cp=None, k=None, rho=None): r'''Calculates Lewis number or `Le` for a fluid with the given parameters. .. math:: Le = \frac{k}{\rho C_p D} = \frac{\alpha}{D} Inputs can be either of the following sets: * Diffusivity and Thermal diffusivity * Diffusivity, heat capacity, thermal conductivity, and density Parameters ---------- D : float Diffusivity of a species, [m^2/s] alpha : float, optional Thermal diffusivity, [m^2/s] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] rho : float, optional Density, [kg/m^3] Returns ------- Le : float Lewis number [] Notes ----- .. math:: Le=\frac{\text{Thermal diffusivity}}{\text{Mass diffusivity}} = \frac{Sc}{Pr} An error is raised if none of the required input sets are provided. Examples -------- >>> Lewis(D=22.6E-6, alpha=19.1E-6) 0.8451327433628318 >>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200) 0.00502815768302494 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition. Berlin; New York:: Springer, 2010. ''' if k and Cp and rho: alpha = k/(rho*Cp) elif alpha: pass else: raise Exception('Insufficient information provided for Le calculation') return alpha/D
[ "def", "Lewis", "(", "D", "=", "None", ",", "alpha", "=", "None", ",", "Cp", "=", "None", ",", "k", "=", "None", ",", "rho", "=", "None", ")", ":", "if", "k", "and", "Cp", "and", "rho", ":", "alpha", "=", "k", "/", "(", "rho", "*", "Cp", ")", "elif", "alpha", ":", "pass", "else", ":", "raise", "Exception", "(", "'Insufficient information provided for Le calculation'", ")", "return", "alpha", "/", "D" ]
r'''Calculates Lewis number or `Le` for a fluid with the given parameters. .. math:: Le = \frac{k}{\rho C_p D} = \frac{\alpha}{D} Inputs can be either of the following sets: * Diffusivity and Thermal diffusivity * Diffusivity, heat capacity, thermal conductivity, and density Parameters ---------- D : float Diffusivity of a species, [m^2/s] alpha : float, optional Thermal diffusivity, [m^2/s] Cp : float, optional Heat capacity, [J/kg/K] k : float, optional Thermal conductivity, [W/m/K] rho : float, optional Density, [kg/m^3] Returns ------- Le : float Lewis number [] Notes ----- .. math:: Le=\frac{\text{Thermal diffusivity}}{\text{Mass diffusivity}} = \frac{Sc}{Pr} An error is raised if none of the required input sets are provided. Examples -------- >>> Lewis(D=22.6E-6, alpha=19.1E-6) 0.8451327433628318 >>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200) 0.00502815768302494 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition. Berlin; New York:: Springer, 2010.
[ "r", "Calculates", "Lewis", "number", "or", "Le", "for", "a", "fluid", "with", "the", "given", "parameters", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L515-L574
8,247
CalebBell/fluids
fluids/core.py
Confinement
def Confinement(D, rhol, rhog, sigma, g=g): r'''Calculates Confinement number or `Co` for a fluid in a channel of diameter `D` with liquid and gas densities `rhol` and `rhog` and surface tension `sigma`, under the influence of gravitational force `g`. .. math:: \text{Co}=\frac{\left[\frac{\sigma}{g(\rho_l-\rho_g)}\right]^{0.5}}{D} Parameters ---------- D : float Diameter of channel, [m] rhol : float Density of liquid phase, [kg/m^3] rhog : float Density of gas phase, [kg/m^3] sigma : float Surface tension between liquid-gas phase, [N/m] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- Co : float Confinement number [-] Notes ----- Used in two-phase pressure drop and heat transfer correlations. First used in [1]_ according to [3]_. .. math:: \text{Co} = \frac{\frac{\text{surface tension force}} {\text{buoyancy force}}}{\text{Channel area}} Examples -------- >>> Confinement(0.001, 1077, 76.5, 4.27E-3) 0.6596978265315191 References ---------- .. [1] Cornwell, Keith, and Peter A. Kew. "Boiling in Small Parallel Channels." In Energy Efficiency in Process Technology, edited by Dr P. A. Pilavachi, 624-638. Springer Netherlands, 1993. doi:10.1007/978-94-011-1454-7_56. .. [2] Kandlikar, Satish G. Heat Transfer and Fluid Flow in Minichannels and Microchannels. Elsevier, 2006. .. [3] Tran, T. N, M. -C Chyu, M. W Wambsganss, and D. M France. Two-Phase Pressure Drop of Refrigerants during Flow Boiling in Small Channels: An Experimental Investigation and Correlation Development." International Journal of Multiphase Flow 26, no. 11 (November 1, 2000): 1739-54. doi:10.1016/S0301-9322(99)00119-6. ''' return (sigma/(g*(rhol-rhog)))**0.5/D
python
def Confinement(D, rhol, rhog, sigma, g=g): r'''Calculates Confinement number or `Co` for a fluid in a channel of diameter `D` with liquid and gas densities `rhol` and `rhog` and surface tension `sigma`, under the influence of gravitational force `g`. .. math:: \text{Co}=\frac{\left[\frac{\sigma}{g(\rho_l-\rho_g)}\right]^{0.5}}{D} Parameters ---------- D : float Diameter of channel, [m] rhol : float Density of liquid phase, [kg/m^3] rhog : float Density of gas phase, [kg/m^3] sigma : float Surface tension between liquid-gas phase, [N/m] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- Co : float Confinement number [-] Notes ----- Used in two-phase pressure drop and heat transfer correlations. First used in [1]_ according to [3]_. .. math:: \text{Co} = \frac{\frac{\text{surface tension force}} {\text{buoyancy force}}}{\text{Channel area}} Examples -------- >>> Confinement(0.001, 1077, 76.5, 4.27E-3) 0.6596978265315191 References ---------- .. [1] Cornwell, Keith, and Peter A. Kew. "Boiling in Small Parallel Channels." In Energy Efficiency in Process Technology, edited by Dr P. A. Pilavachi, 624-638. Springer Netherlands, 1993. doi:10.1007/978-94-011-1454-7_56. .. [2] Kandlikar, Satish G. Heat Transfer and Fluid Flow in Minichannels and Microchannels. Elsevier, 2006. .. [3] Tran, T. N, M. -C Chyu, M. W Wambsganss, and D. M France. Two-Phase Pressure Drop of Refrigerants during Flow Boiling in Small Channels: An Experimental Investigation and Correlation Development." International Journal of Multiphase Flow 26, no. 11 (November 1, 2000): 1739-54. doi:10.1016/S0301-9322(99)00119-6. ''' return (sigma/(g*(rhol-rhog)))**0.5/D
[ "def", "Confinement", "(", "D", ",", "rhol", ",", "rhog", ",", "sigma", ",", "g", "=", "g", ")", ":", "return", "(", "sigma", "/", "(", "g", "*", "(", "rhol", "-", "rhog", ")", ")", ")", "**", "0.5", "/", "D" ]
r'''Calculates Confinement number or `Co` for a fluid in a channel of diameter `D` with liquid and gas densities `rhol` and `rhog` and surface tension `sigma`, under the influence of gravitational force `g`. .. math:: \text{Co}=\frac{\left[\frac{\sigma}{g(\rho_l-\rho_g)}\right]^{0.5}}{D} Parameters ---------- D : float Diameter of channel, [m] rhol : float Density of liquid phase, [kg/m^3] rhog : float Density of gas phase, [kg/m^3] sigma : float Surface tension between liquid-gas phase, [N/m] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- Co : float Confinement number [-] Notes ----- Used in two-phase pressure drop and heat transfer correlations. First used in [1]_ according to [3]_. .. math:: \text{Co} = \frac{\frac{\text{surface tension force}} {\text{buoyancy force}}}{\text{Channel area}} Examples -------- >>> Confinement(0.001, 1077, 76.5, 4.27E-3) 0.6596978265315191 References ---------- .. [1] Cornwell, Keith, and Peter A. Kew. "Boiling in Small Parallel Channels." In Energy Efficiency in Process Technology, edited by Dr P. A. Pilavachi, 624-638. Springer Netherlands, 1993. doi:10.1007/978-94-011-1454-7_56. .. [2] Kandlikar, Satish G. Heat Transfer and Fluid Flow in Minichannels and Microchannels. Elsevier, 2006. .. [3] Tran, T. N, M. -C Chyu, M. W Wambsganss, and D. M France. Two-Phase Pressure Drop of Refrigerants during Flow Boiling in Small Channels: An Experimental Investigation and Correlation Development." International Journal of Multiphase Flow 26, no. 11 (November 1, 2000): 1739-54. doi:10.1016/S0301-9322(99)00119-6.
[ "r", "Calculates", "Confinement", "number", "or", "Co", "for", "a", "fluid", "in", "a", "channel", "of", "diameter", "D", "with", "liquid", "and", "gas", "densities", "rhol", "and", "rhog", "and", "surface", "tension", "sigma", "under", "the", "influence", "of", "gravitational", "force", "g", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L666-L720
8,248
CalebBell/fluids
fluids/core.py
Morton
def Morton(rhol, rhog, mul, sigma, g=g): r'''Calculates Morton number or `Mo` for a liquid and vapor with the specified properties, under the influence of gravitational force `g`. .. math:: Mo = \frac{g \mu_l^4(\rho_l - \rho_g)}{\rho_l^2 \sigma^3} Parameters ---------- rhol : float Density of liquid phase, [kg/m^3] rhog : float Density of gas phase, [kg/m^3] mul : float Viscosity of liquid phase, [Pa*s] sigma : float Surface tension between liquid-gas phase, [N/m] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- Mo : float Morton number, [-] Notes ----- Used in modeling bubbles in liquid. Examples -------- >>> Morton(1077.0, 76.5, 4.27E-3, 0.023) 2.311183104430743e-07 References ---------- .. [1] Kunes, Josef. Dimensionless Physical Quantities in Science and Engineering. Elsevier, 2012. .. [2] Yan, Xiaokang, Kaixin Zheng, Yan Jia, Zhenyong Miao, Lijun Wang, Yijun Cao, and Jiongtian Liu. “Drag Coefficient Prediction of a Single Bubble Rising in Liquids.” Industrial & Engineering Chemistry Research, April 2, 2018. https://doi.org/10.1021/acs.iecr.7b04743. ''' mul2 = mul*mul return g*mul2*mul2*(rhol - rhog)/(rhol*rhol*sigma*sigma*sigma)
python
def Morton(rhol, rhog, mul, sigma, g=g): r'''Calculates Morton number or `Mo` for a liquid and vapor with the specified properties, under the influence of gravitational force `g`. .. math:: Mo = \frac{g \mu_l^4(\rho_l - \rho_g)}{\rho_l^2 \sigma^3} Parameters ---------- rhol : float Density of liquid phase, [kg/m^3] rhog : float Density of gas phase, [kg/m^3] mul : float Viscosity of liquid phase, [Pa*s] sigma : float Surface tension between liquid-gas phase, [N/m] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- Mo : float Morton number, [-] Notes ----- Used in modeling bubbles in liquid. Examples -------- >>> Morton(1077.0, 76.5, 4.27E-3, 0.023) 2.311183104430743e-07 References ---------- .. [1] Kunes, Josef. Dimensionless Physical Quantities in Science and Engineering. Elsevier, 2012. .. [2] Yan, Xiaokang, Kaixin Zheng, Yan Jia, Zhenyong Miao, Lijun Wang, Yijun Cao, and Jiongtian Liu. “Drag Coefficient Prediction of a Single Bubble Rising in Liquids.” Industrial & Engineering Chemistry Research, April 2, 2018. https://doi.org/10.1021/acs.iecr.7b04743. ''' mul2 = mul*mul return g*mul2*mul2*(rhol - rhog)/(rhol*rhol*sigma*sigma*sigma)
[ "def", "Morton", "(", "rhol", ",", "rhog", ",", "mul", ",", "sigma", ",", "g", "=", "g", ")", ":", "mul2", "=", "mul", "*", "mul", "return", "g", "*", "mul2", "*", "mul2", "*", "(", "rhol", "-", "rhog", ")", "/", "(", "rhol", "*", "rhol", "*", "sigma", "*", "sigma", "*", "sigma", ")" ]
r'''Calculates Morton number or `Mo` for a liquid and vapor with the specified properties, under the influence of gravitational force `g`. .. math:: Mo = \frac{g \mu_l^4(\rho_l - \rho_g)}{\rho_l^2 \sigma^3} Parameters ---------- rhol : float Density of liquid phase, [kg/m^3] rhog : float Density of gas phase, [kg/m^3] mul : float Viscosity of liquid phase, [Pa*s] sigma : float Surface tension between liquid-gas phase, [N/m] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- Mo : float Morton number, [-] Notes ----- Used in modeling bubbles in liquid. Examples -------- >>> Morton(1077.0, 76.5, 4.27E-3, 0.023) 2.311183104430743e-07 References ---------- .. [1] Kunes, Josef. Dimensionless Physical Quantities in Science and Engineering. Elsevier, 2012. .. [2] Yan, Xiaokang, Kaixin Zheng, Yan Jia, Zhenyong Miao, Lijun Wang, Yijun Cao, and Jiongtian Liu. “Drag Coefficient Prediction of a Single Bubble Rising in Liquids.” Industrial & Engineering Chemistry Research, April 2, 2018. https://doi.org/10.1021/acs.iecr.7b04743.
[ "r", "Calculates", "Morton", "number", "or", "Mo", "for", "a", "liquid", "and", "vapor", "with", "the", "specified", "properties", "under", "the", "influence", "of", "gravitational", "force", "g", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L723-L767
8,249
CalebBell/fluids
fluids/core.py
Prandtl
def Prandtl(Cp=None, k=None, mu=None, nu=None, rho=None, alpha=None): r'''Calculates Prandtl number or `Pr` for a fluid with the given parameters. .. math:: Pr = \frac{C_p \mu}{k} = \frac{\nu}{\alpha} = \frac{C_p \rho \nu}{k} Inputs can be any of the following sets: * Heat capacity, dynamic viscosity, and thermal conductivity * Thermal diffusivity and kinematic viscosity * Heat capacity, kinematic viscosity, thermal conductivity, and density Parameters ---------- Cp : float Heat capacity, [J/kg/K] k : float Thermal conductivity, [W/m/K] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] rho : float Density, [kg/m^3] alpha : float Thermal diffusivity, [m^2/s] Returns ------- Pr : float Prandtl number [] Notes ----- .. math:: Pr=\frac{\text{kinematic viscosity}}{\text{thermal diffusivity}} = \frac{\text{momentum diffusivity}}{\text{thermal diffusivity}} An error is raised if none of the required input sets are provided. Examples -------- >>> Prandtl(Cp=1637., k=0.010, mu=4.61E-6) 0.754657 >>> Prandtl(Cp=1637., k=0.010, nu=6.4E-7, rho=7.1) 0.7438528 >>> Prandtl(nu=6.3E-7, alpha=9E-7) 0.7000000000000001 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition. Berlin; New York:: Springer, 2010. ''' if k and Cp and mu: return Cp*mu/k elif nu and rho and Cp and k: return nu*rho*Cp/k elif nu and alpha: return nu/alpha else: raise Exception('Insufficient information provided for Pr calculation')
python
def Prandtl(Cp=None, k=None, mu=None, nu=None, rho=None, alpha=None): r'''Calculates Prandtl number or `Pr` for a fluid with the given parameters. .. math:: Pr = \frac{C_p \mu}{k} = \frac{\nu}{\alpha} = \frac{C_p \rho \nu}{k} Inputs can be any of the following sets: * Heat capacity, dynamic viscosity, and thermal conductivity * Thermal diffusivity and kinematic viscosity * Heat capacity, kinematic viscosity, thermal conductivity, and density Parameters ---------- Cp : float Heat capacity, [J/kg/K] k : float Thermal conductivity, [W/m/K] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] rho : float Density, [kg/m^3] alpha : float Thermal diffusivity, [m^2/s] Returns ------- Pr : float Prandtl number [] Notes ----- .. math:: Pr=\frac{\text{kinematic viscosity}}{\text{thermal diffusivity}} = \frac{\text{momentum diffusivity}}{\text{thermal diffusivity}} An error is raised if none of the required input sets are provided. Examples -------- >>> Prandtl(Cp=1637., k=0.010, mu=4.61E-6) 0.754657 >>> Prandtl(Cp=1637., k=0.010, nu=6.4E-7, rho=7.1) 0.7438528 >>> Prandtl(nu=6.3E-7, alpha=9E-7) 0.7000000000000001 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition. Berlin; New York:: Springer, 2010. ''' if k and Cp and mu: return Cp*mu/k elif nu and rho and Cp and k: return nu*rho*Cp/k elif nu and alpha: return nu/alpha else: raise Exception('Insufficient information provided for Pr calculation')
[ "def", "Prandtl", "(", "Cp", "=", "None", ",", "k", "=", "None", ",", "mu", "=", "None", ",", "nu", "=", "None", ",", "rho", "=", "None", ",", "alpha", "=", "None", ")", ":", "if", "k", "and", "Cp", "and", "mu", ":", "return", "Cp", "*", "mu", "/", "k", "elif", "nu", "and", "rho", "and", "Cp", "and", "k", ":", "return", "nu", "*", "rho", "*", "Cp", "/", "k", "elif", "nu", "and", "alpha", ":", "return", "nu", "/", "alpha", "else", ":", "raise", "Exception", "(", "'Insufficient information provided for Pr calculation'", ")" ]
r'''Calculates Prandtl number or `Pr` for a fluid with the given parameters. .. math:: Pr = \frac{C_p \mu}{k} = \frac{\nu}{\alpha} = \frac{C_p \rho \nu}{k} Inputs can be any of the following sets: * Heat capacity, dynamic viscosity, and thermal conductivity * Thermal diffusivity and kinematic viscosity * Heat capacity, kinematic viscosity, thermal conductivity, and density Parameters ---------- Cp : float Heat capacity, [J/kg/K] k : float Thermal conductivity, [W/m/K] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] rho : float Density, [kg/m^3] alpha : float Thermal diffusivity, [m^2/s] Returns ------- Pr : float Prandtl number [] Notes ----- .. math:: Pr=\frac{\text{kinematic viscosity}}{\text{thermal diffusivity}} = \frac{\text{momentum diffusivity}}{\text{thermal diffusivity}} An error is raised if none of the required input sets are provided. Examples -------- >>> Prandtl(Cp=1637., k=0.010, mu=4.61E-6) 0.754657 >>> Prandtl(Cp=1637., k=0.010, nu=6.4E-7, rho=7.1) 0.7438528 >>> Prandtl(nu=6.3E-7, alpha=9E-7) 0.7000000000000001 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition. Berlin; New York:: Springer, 2010.
[ "r", "Calculates", "Prandtl", "number", "or", "Pr", "for", "a", "fluid", "with", "the", "given", "parameters", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L811-L876
8,250
CalebBell/fluids
fluids/core.py
Grashof
def Grashof(L, beta, T1, T2=0, rho=None, mu=None, nu=None, g=g): r'''Calculates Grashof number or `Gr` for a fluid with the given properties, temperature difference, and characteristic length. .. math:: Gr = \frac{g\beta (T_s-T_\infty)L^3}{\nu^2} = \frac{g\beta (T_s-T_\infty)L^3\rho^2}{\mu^2} Inputs either of any of the following sets: * L, beta, T1 and T2, and density `rho` and kinematic viscosity `mu` * L, beta, T1 and T2, and dynamic viscosity `nu` Parameters ---------- L : float Characteristic length [m] beta : float Volumetric thermal expansion coefficient [1/K] T1 : float Temperature 1, usually a film temperature [K] T2 : float, optional Temperature 2, usually a bulk temperature (or 0 if only a difference is provided to the function) [K] rho : float, optional Density, [kg/m^3] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- Gr : float Grashof number [] Notes ----- .. math:: Gr = \frac{\text{Buoyancy forces}}{\text{Viscous forces}} An error is raised if none of the required input sets are provided. Used in free convection problems only. Examples -------- Example 4 of [1]_, p. 1-21 (matches): >>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5) 4656936556.178915 >>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05) 4657491516.530312 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if rho and mu: nu = mu/rho elif not nu: raise Exception('Either density and viscosity, or dynamic viscosity, \ is needed') return g*beta*abs(T2-T1)*L**3/nu**2
python
def Grashof(L, beta, T1, T2=0, rho=None, mu=None, nu=None, g=g): r'''Calculates Grashof number or `Gr` for a fluid with the given properties, temperature difference, and characteristic length. .. math:: Gr = \frac{g\beta (T_s-T_\infty)L^3}{\nu^2} = \frac{g\beta (T_s-T_\infty)L^3\rho^2}{\mu^2} Inputs either of any of the following sets: * L, beta, T1 and T2, and density `rho` and kinematic viscosity `mu` * L, beta, T1 and T2, and dynamic viscosity `nu` Parameters ---------- L : float Characteristic length [m] beta : float Volumetric thermal expansion coefficient [1/K] T1 : float Temperature 1, usually a film temperature [K] T2 : float, optional Temperature 2, usually a bulk temperature (or 0 if only a difference is provided to the function) [K] rho : float, optional Density, [kg/m^3] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- Gr : float Grashof number [] Notes ----- .. math:: Gr = \frac{\text{Buoyancy forces}}{\text{Viscous forces}} An error is raised if none of the required input sets are provided. Used in free convection problems only. Examples -------- Example 4 of [1]_, p. 1-21 (matches): >>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5) 4656936556.178915 >>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05) 4657491516.530312 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if rho and mu: nu = mu/rho elif not nu: raise Exception('Either density and viscosity, or dynamic viscosity, \ is needed') return g*beta*abs(T2-T1)*L**3/nu**2
[ "def", "Grashof", "(", "L", ",", "beta", ",", "T1", ",", "T2", "=", "0", ",", "rho", "=", "None", ",", "mu", "=", "None", ",", "nu", "=", "None", ",", "g", "=", "g", ")", ":", "if", "rho", "and", "mu", ":", "nu", "=", "mu", "/", "rho", "elif", "not", "nu", ":", "raise", "Exception", "(", "'Either density and viscosity, or dynamic viscosity, \\\n is needed'", ")", "return", "g", "*", "beta", "*", "abs", "(", "T2", "-", "T1", ")", "*", "L", "**", "3", "/", "nu", "**", "2" ]
r'''Calculates Grashof number or `Gr` for a fluid with the given properties, temperature difference, and characteristic length. .. math:: Gr = \frac{g\beta (T_s-T_\infty)L^3}{\nu^2} = \frac{g\beta (T_s-T_\infty)L^3\rho^2}{\mu^2} Inputs either of any of the following sets: * L, beta, T1 and T2, and density `rho` and kinematic viscosity `mu` * L, beta, T1 and T2, and dynamic viscosity `nu` Parameters ---------- L : float Characteristic length [m] beta : float Volumetric thermal expansion coefficient [1/K] T1 : float Temperature 1, usually a film temperature [K] T2 : float, optional Temperature 2, usually a bulk temperature (or 0 if only a difference is provided to the function) [K] rho : float, optional Density, [kg/m^3] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] g : float, optional Acceleration due to gravity, [m/s^2] Returns ------- Gr : float Grashof number [] Notes ----- .. math:: Gr = \frac{\text{Buoyancy forces}}{\text{Viscous forces}} An error is raised if none of the required input sets are provided. Used in free convection problems only. Examples -------- Example 4 of [1]_, p. 1-21 (matches): >>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5) 4656936556.178915 >>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05) 4657491516.530312 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006.
[ "r", "Calculates", "Grashof", "number", "or", "Gr", "for", "a", "fluid", "with", "the", "given", "properties", "temperature", "difference", "and", "characteristic", "length", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L879-L946
8,251
CalebBell/fluids
fluids/core.py
Froude
def Froude(V, L, g=g, squared=False): r'''Calculates Froude number `Fr` for velocity `V` and geometric length `L`. If desired, gravity can be specified as well. Normally the function returns the result of the equation below; Froude number is also often said to be defined as the square of the equation below. .. math:: Fr = \frac{V}{\sqrt{gL}} Parameters ---------- V : float Velocity of the particle or fluid, [m/s] L : float Characteristic length, no typical definition [m] g : float, optional Acceleration due to gravity, [m/s^2] squared : bool, optional Whether to return the squared form of Froude number Returns ------- Fr : float Froude number, [-] Notes ----- Many alternate definitions including density ratios have been used. .. math:: Fr = \frac{\text{Inertial Force}}{\text{Gravity Force}} Examples -------- >>> Froude(1.83, L=2., g=1.63) 1.0135432593877318 >>> Froude(1.83, L=2., squared=True) 0.17074638128208924 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' Fr = V/(L*g)**0.5 if squared: Fr *= Fr return Fr
python
def Froude(V, L, g=g, squared=False): r'''Calculates Froude number `Fr` for velocity `V` and geometric length `L`. If desired, gravity can be specified as well. Normally the function returns the result of the equation below; Froude number is also often said to be defined as the square of the equation below. .. math:: Fr = \frac{V}{\sqrt{gL}} Parameters ---------- V : float Velocity of the particle or fluid, [m/s] L : float Characteristic length, no typical definition [m] g : float, optional Acceleration due to gravity, [m/s^2] squared : bool, optional Whether to return the squared form of Froude number Returns ------- Fr : float Froude number, [-] Notes ----- Many alternate definitions including density ratios have been used. .. math:: Fr = \frac{\text{Inertial Force}}{\text{Gravity Force}} Examples -------- >>> Froude(1.83, L=2., g=1.63) 1.0135432593877318 >>> Froude(1.83, L=2., squared=True) 0.17074638128208924 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' Fr = V/(L*g)**0.5 if squared: Fr *= Fr return Fr
[ "def", "Froude", "(", "V", ",", "L", ",", "g", "=", "g", ",", "squared", "=", "False", ")", ":", "Fr", "=", "V", "/", "(", "L", "*", "g", ")", "**", "0.5", "if", "squared", ":", "Fr", "*=", "Fr", "return", "Fr" ]
r'''Calculates Froude number `Fr` for velocity `V` and geometric length `L`. If desired, gravity can be specified as well. Normally the function returns the result of the equation below; Froude number is also often said to be defined as the square of the equation below. .. math:: Fr = \frac{V}{\sqrt{gL}} Parameters ---------- V : float Velocity of the particle or fluid, [m/s] L : float Characteristic length, no typical definition [m] g : float, optional Acceleration due to gravity, [m/s^2] squared : bool, optional Whether to return the squared form of Froude number Returns ------- Fr : float Froude number, [-] Notes ----- Many alternate definitions including density ratios have been used. .. math:: Fr = \frac{\text{Inertial Force}}{\text{Gravity Force}} Examples -------- >>> Froude(1.83, L=2., g=1.63) 1.0135432593877318 >>> Froude(1.83, L=2., squared=True) 0.17074638128208924 References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006.
[ "r", "Calculates", "Froude", "number", "Fr", "for", "velocity", "V", "and", "geometric", "length", "L", ".", "If", "desired", "gravity", "can", "be", "specified", "as", "well", ".", "Normally", "the", "function", "returns", "the", "result", "of", "the", "equation", "below", ";", "Froude", "number", "is", "also", "often", "said", "to", "be", "defined", "as", "the", "square", "of", "the", "equation", "below", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L1028-L1077
8,252
CalebBell/fluids
fluids/core.py
Stokes_number
def Stokes_number(V, Dp, D, rhop, mu): r'''Calculates Stokes Number for a given characteristic velocity `V`, particle diameter `Dp`, characteristic diameter `D`, particle density `rhop`, and fluid viscosity `mu`. .. math:: \text{Stk} = \frac{\rho_p V D_p^2}{18\mu_f D} Parameters ---------- V : float Characteristic velocity (often superficial), [m/s] Dp : float Particle diameter, [m] D : float Characteristic diameter (ex demister wire diameter or cyclone diameter), [m] rhop : float Particle density, [kg/m^3] mu : float Fluid viscosity, [Pa*s] Returns ------- Stk : float Stokes numer, [-] Notes ----- Used in droplet impaction or collection studies. Examples -------- >>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5) 0.5 References ---------- .. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013. .. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A. Al-Masry. "Investigating Droplet Separation Efficiency in Wire-Mesh Mist Eliminators in Bubble Column." Journal of Saudi Chemical Society 14, no. 4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001. ''' return rhop*V*(Dp*Dp)/(18.0*mu*D)
python
def Stokes_number(V, Dp, D, rhop, mu): r'''Calculates Stokes Number for a given characteristic velocity `V`, particle diameter `Dp`, characteristic diameter `D`, particle density `rhop`, and fluid viscosity `mu`. .. math:: \text{Stk} = \frac{\rho_p V D_p^2}{18\mu_f D} Parameters ---------- V : float Characteristic velocity (often superficial), [m/s] Dp : float Particle diameter, [m] D : float Characteristic diameter (ex demister wire diameter or cyclone diameter), [m] rhop : float Particle density, [kg/m^3] mu : float Fluid viscosity, [Pa*s] Returns ------- Stk : float Stokes numer, [-] Notes ----- Used in droplet impaction or collection studies. Examples -------- >>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5) 0.5 References ---------- .. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013. .. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A. Al-Masry. "Investigating Droplet Separation Efficiency in Wire-Mesh Mist Eliminators in Bubble Column." Journal of Saudi Chemical Society 14, no. 4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001. ''' return rhop*V*(Dp*Dp)/(18.0*mu*D)
[ "def", "Stokes_number", "(", "V", ",", "Dp", ",", "D", ",", "rhop", ",", "mu", ")", ":", "return", "rhop", "*", "V", "*", "(", "Dp", "*", "Dp", ")", "/", "(", "18.0", "*", "mu", "*", "D", ")" ]
r'''Calculates Stokes Number for a given characteristic velocity `V`, particle diameter `Dp`, characteristic diameter `D`, particle density `rhop`, and fluid viscosity `mu`. .. math:: \text{Stk} = \frac{\rho_p V D_p^2}{18\mu_f D} Parameters ---------- V : float Characteristic velocity (often superficial), [m/s] Dp : float Particle diameter, [m] D : float Characteristic diameter (ex demister wire diameter or cyclone diameter), [m] rhop : float Particle density, [kg/m^3] mu : float Fluid viscosity, [Pa*s] Returns ------- Stk : float Stokes numer, [-] Notes ----- Used in droplet impaction or collection studies. Examples -------- >>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5) 0.5 References ---------- .. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013. .. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A. Al-Masry. "Investigating Droplet Separation Efficiency in Wire-Mesh Mist Eliminators in Bubble Column." Journal of Saudi Chemical Society 14, no. 4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001.
[ "r", "Calculates", "Stokes", "Number", "for", "a", "given", "characteristic", "velocity", "V", "particle", "diameter", "Dp", "characteristic", "diameter", "D", "particle", "density", "rhop", "and", "fluid", "viscosity", "mu", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L1644-L1688
8,253
CalebBell/fluids
fluids/core.py
Suratman
def Suratman(L, rho, mu, sigma): r'''Calculates Suratman number, `Su`, for a fluid with the given characteristic length, density, viscosity, and surface tension. .. math:: \text{Su} = \frac{\rho\sigma L}{\mu^2} Parameters ---------- L : float Characteristic length [m] rho : float Density of fluid, [kg/m^3] mu : float Viscosity of fluid, [Pa*s] sigma : float Surface tension, [N/m] Returns ------- Su : float Suratman number [] Notes ----- Also known as Laplace number. Used in two-phase flow, especially the bubbly-slug regime. No confusion regarding the definition of this group has been observed. .. math:: \text{Su} = \frac{\text{Re}^2}{\text{We}} =\frac{\text{Inertia}\cdot \text{Surface tension} }{\text{(viscous forces)}^2} The oldest reference to this group found by the author is in 1963, from [2]_. Examples -------- >>> Suratman(1E-4, 1000., 1E-3, 1E-1) 10000.0 References ---------- .. [1] Sen, Nilava. "Suratman Number in Bubble-to-Slug Flow Pattern Transition under Microgravity." Acta Astronautica 65, no. 3-4 (August 2009): 423-28. doi:10.1016/j.actaastro.2009.02.013. .. [2] Catchpole, John P., and George. Fulford. "DIMENSIONLESS GROUPS." Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60. doi:10.1021/ie50675a012. ''' return rho*sigma*L/(mu*mu)
python
def Suratman(L, rho, mu, sigma): r'''Calculates Suratman number, `Su`, for a fluid with the given characteristic length, density, viscosity, and surface tension. .. math:: \text{Su} = \frac{\rho\sigma L}{\mu^2} Parameters ---------- L : float Characteristic length [m] rho : float Density of fluid, [kg/m^3] mu : float Viscosity of fluid, [Pa*s] sigma : float Surface tension, [N/m] Returns ------- Su : float Suratman number [] Notes ----- Also known as Laplace number. Used in two-phase flow, especially the bubbly-slug regime. No confusion regarding the definition of this group has been observed. .. math:: \text{Su} = \frac{\text{Re}^2}{\text{We}} =\frac{\text{Inertia}\cdot \text{Surface tension} }{\text{(viscous forces)}^2} The oldest reference to this group found by the author is in 1963, from [2]_. Examples -------- >>> Suratman(1E-4, 1000., 1E-3, 1E-1) 10000.0 References ---------- .. [1] Sen, Nilava. "Suratman Number in Bubble-to-Slug Flow Pattern Transition under Microgravity." Acta Astronautica 65, no. 3-4 (August 2009): 423-28. doi:10.1016/j.actaastro.2009.02.013. .. [2] Catchpole, John P., and George. Fulford. "DIMENSIONLESS GROUPS." Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60. doi:10.1021/ie50675a012. ''' return rho*sigma*L/(mu*mu)
[ "def", "Suratman", "(", "L", ",", "rho", ",", "mu", ",", "sigma", ")", ":", "return", "rho", "*", "sigma", "*", "L", "/", "(", "mu", "*", "mu", ")" ]
r'''Calculates Suratman number, `Su`, for a fluid with the given characteristic length, density, viscosity, and surface tension. .. math:: \text{Su} = \frac{\rho\sigma L}{\mu^2} Parameters ---------- L : float Characteristic length [m] rho : float Density of fluid, [kg/m^3] mu : float Viscosity of fluid, [Pa*s] sigma : float Surface tension, [N/m] Returns ------- Su : float Suratman number [] Notes ----- Also known as Laplace number. Used in two-phase flow, especially the bubbly-slug regime. No confusion regarding the definition of this group has been observed. .. math:: \text{Su} = \frac{\text{Re}^2}{\text{We}} =\frac{\text{Inertia}\cdot \text{Surface tension} }{\text{(viscous forces)}^2} The oldest reference to this group found by the author is in 1963, from [2]_. Examples -------- >>> Suratman(1E-4, 1000., 1E-3, 1E-1) 10000.0 References ---------- .. [1] Sen, Nilava. "Suratman Number in Bubble-to-Slug Flow Pattern Transition under Microgravity." Acta Astronautica 65, no. 3-4 (August 2009): 423-28. doi:10.1016/j.actaastro.2009.02.013. .. [2] Catchpole, John P., and George. Fulford. "DIMENSIONLESS GROUPS." Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60. doi:10.1021/ie50675a012.
[ "r", "Calculates", "Suratman", "number", "Su", "for", "a", "fluid", "with", "the", "given", "characteristic", "length", "density", "viscosity", "and", "surface", "tension", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L1828-L1878
8,254
CalebBell/fluids
fluids/core.py
nu_mu_converter
def nu_mu_converter(rho, mu=None, nu=None): r'''Calculates either kinematic or dynamic viscosity, depending on inputs. Used when one type of viscosity is known as well as density, to obtain the other type. Raises an error if both types of viscosity or neither type of viscosity is provided. .. math:: \nu = \frac{\mu}{\rho} .. math:: \mu = \nu\rho Parameters ---------- rho : float Density, [kg/m^3] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] Returns ------- mu or nu : float Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s Examples -------- >>> nu_mu_converter(998., nu=1.0E-6) 0.000998 References ---------- .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if (nu and mu) or not rho or (not nu and not mu): raise Exception('Inputs must be rho and one of mu and nu.') if mu: return mu/rho elif nu: return nu*rho
python
def nu_mu_converter(rho, mu=None, nu=None): r'''Calculates either kinematic or dynamic viscosity, depending on inputs. Used when one type of viscosity is known as well as density, to obtain the other type. Raises an error if both types of viscosity or neither type of viscosity is provided. .. math:: \nu = \frac{\mu}{\rho} .. math:: \mu = \nu\rho Parameters ---------- rho : float Density, [kg/m^3] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] Returns ------- mu or nu : float Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s Examples -------- >>> nu_mu_converter(998., nu=1.0E-6) 0.000998 References ---------- .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006. ''' if (nu and mu) or not rho or (not nu and not mu): raise Exception('Inputs must be rho and one of mu and nu.') if mu: return mu/rho elif nu: return nu*rho
[ "def", "nu_mu_converter", "(", "rho", ",", "mu", "=", "None", ",", "nu", "=", "None", ")", ":", "if", "(", "nu", "and", "mu", ")", "or", "not", "rho", "or", "(", "not", "nu", "and", "not", "mu", ")", ":", "raise", "Exception", "(", "'Inputs must be rho and one of mu and nu.'", ")", "if", "mu", ":", "return", "mu", "/", "rho", "elif", "nu", ":", "return", "nu", "*", "rho" ]
r'''Calculates either kinematic or dynamic viscosity, depending on inputs. Used when one type of viscosity is known as well as density, to obtain the other type. Raises an error if both types of viscosity or neither type of viscosity is provided. .. math:: \nu = \frac{\mu}{\rho} .. math:: \mu = \nu\rho Parameters ---------- rho : float Density, [kg/m^3] mu : float, optional Dynamic viscosity, [Pa*s] nu : float, optional Kinematic viscosity, [m^2/s] Returns ------- mu or nu : float Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s Examples -------- >>> nu_mu_converter(998., nu=1.0E-6) 0.000998 References ---------- .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and Applications. Boston: McGraw Hill Higher Education, 2006.
[ "r", "Calculates", "either", "kinematic", "or", "dynamic", "viscosity", "depending", "on", "inputs", ".", "Used", "when", "one", "type", "of", "viscosity", "is", "known", "as", "well", "as", "density", "to", "obtain", "the", "other", "type", ".", "Raises", "an", "error", "if", "both", "types", "of", "viscosity", "or", "neither", "type", "of", "viscosity", "is", "provided", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L2158-L2199
8,255
CalebBell/fluids
fluids/core.py
Engauge_2d_parser
def Engauge_2d_parser(lines, flat=False): '''Not exposed function to read a 2D file generated by engauge-digitizer; for curve fitting. ''' z_values = [] x_lists = [] y_lists = [] working_xs = [] working_ys = [] new_curve = True for line in lines: if line.strip() == '': new_curve = True elif new_curve: z = float(line.split(',')[1]) z_values.append(z) if working_xs and working_ys: x_lists.append(working_xs) y_lists.append(working_ys) working_xs = [] working_ys = [] new_curve = False else: x, y = [float(i) for i in line.strip().split(',')] working_xs.append(x) working_ys.append(y) x_lists.append(working_xs) y_lists.append(working_ys) if flat: all_zs = [] all_xs = [] all_ys = [] for z, xs, ys in zip(z_values, x_lists, y_lists): for x, y in zip(xs, ys): all_zs.append(z) all_xs.append(x) all_ys.append(y) return all_zs, all_xs, all_ys return z_values, x_lists, y_lists
python
def Engauge_2d_parser(lines, flat=False): '''Not exposed function to read a 2D file generated by engauge-digitizer; for curve fitting. ''' z_values = [] x_lists = [] y_lists = [] working_xs = [] working_ys = [] new_curve = True for line in lines: if line.strip() == '': new_curve = True elif new_curve: z = float(line.split(',')[1]) z_values.append(z) if working_xs and working_ys: x_lists.append(working_xs) y_lists.append(working_ys) working_xs = [] working_ys = [] new_curve = False else: x, y = [float(i) for i in line.strip().split(',')] working_xs.append(x) working_ys.append(y) x_lists.append(working_xs) y_lists.append(working_ys) if flat: all_zs = [] all_xs = [] all_ys = [] for z, xs, ys in zip(z_values, x_lists, y_lists): for x, y in zip(xs, ys): all_zs.append(z) all_xs.append(x) all_ys.append(y) return all_zs, all_xs, all_ys return z_values, x_lists, y_lists
[ "def", "Engauge_2d_parser", "(", "lines", ",", "flat", "=", "False", ")", ":", "z_values", "=", "[", "]", "x_lists", "=", "[", "]", "y_lists", "=", "[", "]", "working_xs", "=", "[", "]", "working_ys", "=", "[", "]", "new_curve", "=", "True", "for", "line", "in", "lines", ":", "if", "line", ".", "strip", "(", ")", "==", "''", ":", "new_curve", "=", "True", "elif", "new_curve", ":", "z", "=", "float", "(", "line", ".", "split", "(", "','", ")", "[", "1", "]", ")", "z_values", ".", "append", "(", "z", ")", "if", "working_xs", "and", "working_ys", ":", "x_lists", ".", "append", "(", "working_xs", ")", "y_lists", ".", "append", "(", "working_ys", ")", "working_xs", "=", "[", "]", "working_ys", "=", "[", "]", "new_curve", "=", "False", "else", ":", "x", ",", "y", "=", "[", "float", "(", "i", ")", "for", "i", "in", "line", ".", "strip", "(", ")", ".", "split", "(", "','", ")", "]", "working_xs", ".", "append", "(", "x", ")", "working_ys", ".", "append", "(", "y", ")", "x_lists", ".", "append", "(", "working_xs", ")", "y_lists", ".", "append", "(", "working_ys", ")", "if", "flat", ":", "all_zs", "=", "[", "]", "all_xs", "=", "[", "]", "all_ys", "=", "[", "]", "for", "z", ",", "xs", ",", "ys", "in", "zip", "(", "z_values", ",", "x_lists", ",", "y_lists", ")", ":", "for", "x", ",", "y", "in", "zip", "(", "xs", ",", "ys", ")", ":", "all_zs", ".", "append", "(", "z", ")", "all_xs", ".", "append", "(", "x", ")", "all_ys", ".", "append", "(", "y", ")", "return", "all_zs", ",", "all_xs", ",", "all_ys", "return", "z_values", ",", "x_lists", ",", "y_lists" ]
Not exposed function to read a 2D file generated by engauge-digitizer; for curve fitting.
[ "Not", "exposed", "function", "to", "read", "a", "2D", "file", "generated", "by", "engauge", "-", "digitizer", ";", "for", "curve", "fitting", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L2869-L2910
8,256
CalebBell/fluids
fluids/compressible.py
isothermal_work_compression
def isothermal_work_compression(P1, P2, T, Z=1): r'''Calculates the work of compression or expansion of a gas going through an isothermal process. .. math:: W = zRT\ln\left(\frac{P_2}{P_1}\right) Parameters ---------- P1 : float Inlet pressure, [Pa] P2 : float Outlet pressure, [Pa] T : float Temperature of the gas going through an isothermal process, [K] Z : float Constant compressibility factor of the gas, [-] Returns ------- W : float Work performed per mole of gas compressed/expanded [J/mol] Notes ----- The full derivation with all forms is as follows: .. math:: W = \int_{P_1}^{P_2} V dP = zRT\int_{P_1}^{P_2} \frac{1}{P} dP .. math:: W = zRT\ln\left(\frac{P_2}{P_1}\right) = P_1 V_1 \ln\left(\frac{P_2} {P_1}\right) = P_2 V_2 \ln\left(\frac{P_2}{P_1}\right) The substitutions are according to the ideal gas law with compressibility: .. math: PV = ZRT The work of compression/expansion is the change in enthalpy of the gas. Returns negative values for expansion and positive values for compression. An average compressibility factor can be used where Z changes. For further accuracy, this expression can be used repeatedly with small changes in pressure and the work from each step summed. This is the best possible case for compression; all actual compresssors require more work to do the compression. By making the compression take a large number of stages and cooling the gas between stages, this can be approached reasonable closely. Integrally geared compressors are often used for this purpose. Examples -------- >>> isothermal_work_compression(1E5, 1E6, 300) 5743.427304244769 References ---------- .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf Professional Publishing, 2009. ''' return Z*R*T*log(P2/P1)
python
def isothermal_work_compression(P1, P2, T, Z=1): r'''Calculates the work of compression or expansion of a gas going through an isothermal process. .. math:: W = zRT\ln\left(\frac{P_2}{P_1}\right) Parameters ---------- P1 : float Inlet pressure, [Pa] P2 : float Outlet pressure, [Pa] T : float Temperature of the gas going through an isothermal process, [K] Z : float Constant compressibility factor of the gas, [-] Returns ------- W : float Work performed per mole of gas compressed/expanded [J/mol] Notes ----- The full derivation with all forms is as follows: .. math:: W = \int_{P_1}^{P_2} V dP = zRT\int_{P_1}^{P_2} \frac{1}{P} dP .. math:: W = zRT\ln\left(\frac{P_2}{P_1}\right) = P_1 V_1 \ln\left(\frac{P_2} {P_1}\right) = P_2 V_2 \ln\left(\frac{P_2}{P_1}\right) The substitutions are according to the ideal gas law with compressibility: .. math: PV = ZRT The work of compression/expansion is the change in enthalpy of the gas. Returns negative values for expansion and positive values for compression. An average compressibility factor can be used where Z changes. For further accuracy, this expression can be used repeatedly with small changes in pressure and the work from each step summed. This is the best possible case for compression; all actual compresssors require more work to do the compression. By making the compression take a large number of stages and cooling the gas between stages, this can be approached reasonable closely. Integrally geared compressors are often used for this purpose. Examples -------- >>> isothermal_work_compression(1E5, 1E6, 300) 5743.427304244769 References ---------- .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf Professional Publishing, 2009. ''' return Z*R*T*log(P2/P1)
[ "def", "isothermal_work_compression", "(", "P1", ",", "P2", ",", "T", ",", "Z", "=", "1", ")", ":", "return", "Z", "*", "R", "*", "T", "*", "log", "(", "P2", "/", "P1", ")" ]
r'''Calculates the work of compression or expansion of a gas going through an isothermal process. .. math:: W = zRT\ln\left(\frac{P_2}{P_1}\right) Parameters ---------- P1 : float Inlet pressure, [Pa] P2 : float Outlet pressure, [Pa] T : float Temperature of the gas going through an isothermal process, [K] Z : float Constant compressibility factor of the gas, [-] Returns ------- W : float Work performed per mole of gas compressed/expanded [J/mol] Notes ----- The full derivation with all forms is as follows: .. math:: W = \int_{P_1}^{P_2} V dP = zRT\int_{P_1}^{P_2} \frac{1}{P} dP .. math:: W = zRT\ln\left(\frac{P_2}{P_1}\right) = P_1 V_1 \ln\left(\frac{P_2} {P_1}\right) = P_2 V_2 \ln\left(\frac{P_2}{P_1}\right) The substitutions are according to the ideal gas law with compressibility: .. math: PV = ZRT The work of compression/expansion is the change in enthalpy of the gas. Returns negative values for expansion and positive values for compression. An average compressibility factor can be used where Z changes. For further accuracy, this expression can be used repeatedly with small changes in pressure and the work from each step summed. This is the best possible case for compression; all actual compresssors require more work to do the compression. By making the compression take a large number of stages and cooling the gas between stages, this can be approached reasonable closely. Integrally geared compressors are often used for this purpose. Examples -------- >>> isothermal_work_compression(1E5, 1E6, 300) 5743.427304244769 References ---------- .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf Professional Publishing, 2009.
[ "r", "Calculates", "the", "work", "of", "compression", "or", "expansion", "of", "a", "gas", "going", "through", "an", "isothermal", "process", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L38-L102
8,257
CalebBell/fluids
fluids/compressible.py
isentropic_T_rise_compression
def isentropic_T_rise_compression(T1, P1, P2, k, eta=1): r'''Calculates the increase in temperature of a fluid which is compressed or expanded under isentropic, adiabatic conditions assuming constant Cp and Cv. The polytropic model is the same equation; just provide `n` instead of `k` and use a polytropic efficienty for `eta` instead of a isentropic efficiency. .. math:: T_2 = T_1 + \frac{\Delta T_s}{\eta_s} = T_1 \left\{1 + \frac{1} {\eta_s}\left[\left(\frac{P_2}{P_1}\right)^{(k-1)/k}-1\right]\right\} Parameters ---------- T1 : float Initial temperature of gas [K] P1 : float Initial pressure of gas [Pa] P2 : float Final pressure of gas [Pa] k : float Isentropic exponent of the gas (Cp/Cv) or polytropic exponent `n` to use this as a polytropic model instead [-] eta : float Isentropic efficiency of the process or polytropic efficiency of the process to use this as a polytropic model instead [-] Returns ------- T2 : float Final temperature of gas [K] Notes ----- For the ideal case (`eta`=1), the model simplifies to: .. math:: \frac{T_2}{T_1} = \left(\frac{P_2}{P_1}\right)^{(k-1)/k} Examples -------- >>> isentropic_T_rise_compression(286.8, 54050, 432400, 1.4) 519.5230938217768 References ---------- .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf Professional Publishing, 2009. .. [2] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors Suppliers Association, Tulsa, OK, 2012. ''' dT = T1*((P2/P1)**((k - 1.0)/k) - 1.0)/eta return T1 + dT
python
def isentropic_T_rise_compression(T1, P1, P2, k, eta=1): r'''Calculates the increase in temperature of a fluid which is compressed or expanded under isentropic, adiabatic conditions assuming constant Cp and Cv. The polytropic model is the same equation; just provide `n` instead of `k` and use a polytropic efficienty for `eta` instead of a isentropic efficiency. .. math:: T_2 = T_1 + \frac{\Delta T_s}{\eta_s} = T_1 \left\{1 + \frac{1} {\eta_s}\left[\left(\frac{P_2}{P_1}\right)^{(k-1)/k}-1\right]\right\} Parameters ---------- T1 : float Initial temperature of gas [K] P1 : float Initial pressure of gas [Pa] P2 : float Final pressure of gas [Pa] k : float Isentropic exponent of the gas (Cp/Cv) or polytropic exponent `n` to use this as a polytropic model instead [-] eta : float Isentropic efficiency of the process or polytropic efficiency of the process to use this as a polytropic model instead [-] Returns ------- T2 : float Final temperature of gas [K] Notes ----- For the ideal case (`eta`=1), the model simplifies to: .. math:: \frac{T_2}{T_1} = \left(\frac{P_2}{P_1}\right)^{(k-1)/k} Examples -------- >>> isentropic_T_rise_compression(286.8, 54050, 432400, 1.4) 519.5230938217768 References ---------- .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf Professional Publishing, 2009. .. [2] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors Suppliers Association, Tulsa, OK, 2012. ''' dT = T1*((P2/P1)**((k - 1.0)/k) - 1.0)/eta return T1 + dT
[ "def", "isentropic_T_rise_compression", "(", "T1", ",", "P1", ",", "P2", ",", "k", ",", "eta", "=", "1", ")", ":", "dT", "=", "T1", "*", "(", "(", "P2", "/", "P1", ")", "**", "(", "(", "k", "-", "1.0", ")", "/", "k", ")", "-", "1.0", ")", "/", "eta", "return", "T1", "+", "dT" ]
r'''Calculates the increase in temperature of a fluid which is compressed or expanded under isentropic, adiabatic conditions assuming constant Cp and Cv. The polytropic model is the same equation; just provide `n` instead of `k` and use a polytropic efficienty for `eta` instead of a isentropic efficiency. .. math:: T_2 = T_1 + \frac{\Delta T_s}{\eta_s} = T_1 \left\{1 + \frac{1} {\eta_s}\left[\left(\frac{P_2}{P_1}\right)^{(k-1)/k}-1\right]\right\} Parameters ---------- T1 : float Initial temperature of gas [K] P1 : float Initial pressure of gas [Pa] P2 : float Final pressure of gas [Pa] k : float Isentropic exponent of the gas (Cp/Cv) or polytropic exponent `n` to use this as a polytropic model instead [-] eta : float Isentropic efficiency of the process or polytropic efficiency of the process to use this as a polytropic model instead [-] Returns ------- T2 : float Final temperature of gas [K] Notes ----- For the ideal case (`eta`=1), the model simplifies to: .. math:: \frac{T_2}{T_1} = \left(\frac{P_2}{P_1}\right)^{(k-1)/k} Examples -------- >>> isentropic_T_rise_compression(286.8, 54050, 432400, 1.4) 519.5230938217768 References ---------- .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf Professional Publishing, 2009. .. [2] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors Suppliers Association, Tulsa, OK, 2012.
[ "r", "Calculates", "the", "increase", "in", "temperature", "of", "a", "fluid", "which", "is", "compressed", "or", "expanded", "under", "isentropic", "adiabatic", "conditions", "assuming", "constant", "Cp", "and", "Cv", ".", "The", "polytropic", "model", "is", "the", "same", "equation", ";", "just", "provide", "n", "instead", "of", "k", "and", "use", "a", "polytropic", "efficienty", "for", "eta", "instead", "of", "a", "isentropic", "efficiency", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L212-L264
8,258
CalebBell/fluids
fluids/compressible.py
isentropic_efficiency
def isentropic_efficiency(P1, P2, k, eta_s=None, eta_p=None): r'''Calculates either isentropic or polytropic efficiency from the other type of efficiency. .. math:: \eta_s = \frac{(P_2/P_1)^{(k-1)/k}-1} {(P_2/P_1)^{\frac{k-1}{k\eta_p}}-1} .. math:: \eta_p = \frac{\left(k - 1\right) \log{\left (\frac{P_{2}}{P_{1}} \right )}}{k \log{\left (\frac{1}{\eta_{s}} \left(\eta_{s} + \left(\frac{P_{2}}{P_{1}}\right)^{\frac{1}{k} \left(k - 1\right)} - 1\right) \right )}} Parameters ---------- P1 : float Initial pressure of gas [Pa] P2 : float Final pressure of gas [Pa] k : float Isentropic exponent of the gas (Cp/Cv) [-] eta_s : float, optional Isentropic (adiabatic) efficiency of the process, [-] eta_p : float, optional Polytropic efficiency of the process, [-] Returns ------- eta_s or eta_p : float Isentropic or polytropic efficiency, depending on input, [-] Notes ----- The form for obtained `eta_p` from `eta_s` was derived with SymPy. Examples -------- >>> isentropic_efficiency(1E5, 1E6, 1.4, eta_p=0.78) 0.7027614191263858 References ---------- .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf Professional Publishing, 2009. ''' if eta_s is None and eta_p: return ((P2/P1)**((k-1.0)/k)-1.0)/((P2/P1)**((k-1.0)/(k*eta_p))-1.0) elif eta_p is None and eta_s: return (k - 1.0)*log(P2/P1)/(k*log( (eta_s + (P2/P1)**((k - 1.0)/k) - 1.0)/eta_s)) else: raise Exception('Either eta_s or eta_p is required')
python
def isentropic_efficiency(P1, P2, k, eta_s=None, eta_p=None): r'''Calculates either isentropic or polytropic efficiency from the other type of efficiency. .. math:: \eta_s = \frac{(P_2/P_1)^{(k-1)/k}-1} {(P_2/P_1)^{\frac{k-1}{k\eta_p}}-1} .. math:: \eta_p = \frac{\left(k - 1\right) \log{\left (\frac{P_{2}}{P_{1}} \right )}}{k \log{\left (\frac{1}{\eta_{s}} \left(\eta_{s} + \left(\frac{P_{2}}{P_{1}}\right)^{\frac{1}{k} \left(k - 1\right)} - 1\right) \right )}} Parameters ---------- P1 : float Initial pressure of gas [Pa] P2 : float Final pressure of gas [Pa] k : float Isentropic exponent of the gas (Cp/Cv) [-] eta_s : float, optional Isentropic (adiabatic) efficiency of the process, [-] eta_p : float, optional Polytropic efficiency of the process, [-] Returns ------- eta_s or eta_p : float Isentropic or polytropic efficiency, depending on input, [-] Notes ----- The form for obtained `eta_p` from `eta_s` was derived with SymPy. Examples -------- >>> isentropic_efficiency(1E5, 1E6, 1.4, eta_p=0.78) 0.7027614191263858 References ---------- .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf Professional Publishing, 2009. ''' if eta_s is None and eta_p: return ((P2/P1)**((k-1.0)/k)-1.0)/((P2/P1)**((k-1.0)/(k*eta_p))-1.0) elif eta_p is None and eta_s: return (k - 1.0)*log(P2/P1)/(k*log( (eta_s + (P2/P1)**((k - 1.0)/k) - 1.0)/eta_s)) else: raise Exception('Either eta_s or eta_p is required')
[ "def", "isentropic_efficiency", "(", "P1", ",", "P2", ",", "k", ",", "eta_s", "=", "None", ",", "eta_p", "=", "None", ")", ":", "if", "eta_s", "is", "None", "and", "eta_p", ":", "return", "(", "(", "P2", "/", "P1", ")", "**", "(", "(", "k", "-", "1.0", ")", "/", "k", ")", "-", "1.0", ")", "/", "(", "(", "P2", "/", "P1", ")", "**", "(", "(", "k", "-", "1.0", ")", "/", "(", "k", "*", "eta_p", ")", ")", "-", "1.0", ")", "elif", "eta_p", "is", "None", "and", "eta_s", ":", "return", "(", "k", "-", "1.0", ")", "*", "log", "(", "P2", "/", "P1", ")", "/", "(", "k", "*", "log", "(", "(", "eta_s", "+", "(", "P2", "/", "P1", ")", "**", "(", "(", "k", "-", "1.0", ")", "/", "k", ")", "-", "1.0", ")", "/", "eta_s", ")", ")", "else", ":", "raise", "Exception", "(", "'Either eta_s or eta_p is required'", ")" ]
r'''Calculates either isentropic or polytropic efficiency from the other type of efficiency. .. math:: \eta_s = \frac{(P_2/P_1)^{(k-1)/k}-1} {(P_2/P_1)^{\frac{k-1}{k\eta_p}}-1} .. math:: \eta_p = \frac{\left(k - 1\right) \log{\left (\frac{P_{2}}{P_{1}} \right )}}{k \log{\left (\frac{1}{\eta_{s}} \left(\eta_{s} + \left(\frac{P_{2}}{P_{1}}\right)^{\frac{1}{k} \left(k - 1\right)} - 1\right) \right )}} Parameters ---------- P1 : float Initial pressure of gas [Pa] P2 : float Final pressure of gas [Pa] k : float Isentropic exponent of the gas (Cp/Cv) [-] eta_s : float, optional Isentropic (adiabatic) efficiency of the process, [-] eta_p : float, optional Polytropic efficiency of the process, [-] Returns ------- eta_s or eta_p : float Isentropic or polytropic efficiency, depending on input, [-] Notes ----- The form for obtained `eta_p` from `eta_s` was derived with SymPy. Examples -------- >>> isentropic_efficiency(1E5, 1E6, 1.4, eta_p=0.78) 0.7027614191263858 References ---------- .. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf Professional Publishing, 2009.
[ "r", "Calculates", "either", "isentropic", "or", "polytropic", "efficiency", "from", "the", "other", "type", "of", "efficiency", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L267-L320
8,259
CalebBell/fluids
fluids/compressible.py
P_isothermal_critical_flow
def P_isothermal_critical_flow(P, fd, D, L): r'''Calculates critical flow pressure `Pcf` for a fluid flowing isothermally and suffering pressure drop caused by a pipe's friction factor. .. math:: P_2 = P_{1} e^{\frac{1}{2 D} \left(D \left(\operatorname{LambertW} {\left (- e^{\frac{1}{D} \left(- D - L f_d\right)} \right )} + 1\right) + L f_d\right)} Parameters ---------- P : float Inlet pressure [Pa] fd : float Darcy friction factor for flow in pipe [-] D : float Diameter of pipe, [m] L : float Length of pipe, [m] Returns ------- Pcf : float Critical flow pressure of a compressible gas flowing from `P1` to `Pcf` in a tube of length L and friction factor `fd` [Pa] Notes ----- Assumes isothermal flow. Developed based on the `isothermal_gas` model, using SymPy. The isothermal gas model is solved for maximum mass flow rate; any pressure drop under it is impossible due to the formation of a shock wave. Examples -------- >>> P_isothermal_critical_flow(P=1E6, fd=0.00185, L=1000., D=0.5) 389699.7317645518 References ---------- .. [1] Wilkes, James O. Fluid Mechanics for Chemical Engineers with Microfluidics and CFD. 2 edition. Upper Saddle River, NJ: Prentice Hall, 2005. ''' # Correct branch of lambertw found by trial and error lambert_term = float(lambertw(-exp((-D - L*fd)/D), -1).real) return P*exp((D*(lambert_term + 1.0) + L*fd)/(2.0*D))
python
def P_isothermal_critical_flow(P, fd, D, L): r'''Calculates critical flow pressure `Pcf` for a fluid flowing isothermally and suffering pressure drop caused by a pipe's friction factor. .. math:: P_2 = P_{1} e^{\frac{1}{2 D} \left(D \left(\operatorname{LambertW} {\left (- e^{\frac{1}{D} \left(- D - L f_d\right)} \right )} + 1\right) + L f_d\right)} Parameters ---------- P : float Inlet pressure [Pa] fd : float Darcy friction factor for flow in pipe [-] D : float Diameter of pipe, [m] L : float Length of pipe, [m] Returns ------- Pcf : float Critical flow pressure of a compressible gas flowing from `P1` to `Pcf` in a tube of length L and friction factor `fd` [Pa] Notes ----- Assumes isothermal flow. Developed based on the `isothermal_gas` model, using SymPy. The isothermal gas model is solved for maximum mass flow rate; any pressure drop under it is impossible due to the formation of a shock wave. Examples -------- >>> P_isothermal_critical_flow(P=1E6, fd=0.00185, L=1000., D=0.5) 389699.7317645518 References ---------- .. [1] Wilkes, James O. Fluid Mechanics for Chemical Engineers with Microfluidics and CFD. 2 edition. Upper Saddle River, NJ: Prentice Hall, 2005. ''' # Correct branch of lambertw found by trial and error lambert_term = float(lambertw(-exp((-D - L*fd)/D), -1).real) return P*exp((D*(lambert_term + 1.0) + L*fd)/(2.0*D))
[ "def", "P_isothermal_critical_flow", "(", "P", ",", "fd", ",", "D", ",", "L", ")", ":", "# Correct branch of lambertw found by trial and error", "lambert_term", "=", "float", "(", "lambertw", "(", "-", "exp", "(", "(", "-", "D", "-", "L", "*", "fd", ")", "/", "D", ")", ",", "-", "1", ")", ".", "real", ")", "return", "P", "*", "exp", "(", "(", "D", "*", "(", "lambert_term", "+", "1.0", ")", "+", "L", "*", "fd", ")", "/", "(", "2.0", "*", "D", ")", ")" ]
r'''Calculates critical flow pressure `Pcf` for a fluid flowing isothermally and suffering pressure drop caused by a pipe's friction factor. .. math:: P_2 = P_{1} e^{\frac{1}{2 D} \left(D \left(\operatorname{LambertW} {\left (- e^{\frac{1}{D} \left(- D - L f_d\right)} \right )} + 1\right) + L f_d\right)} Parameters ---------- P : float Inlet pressure [Pa] fd : float Darcy friction factor for flow in pipe [-] D : float Diameter of pipe, [m] L : float Length of pipe, [m] Returns ------- Pcf : float Critical flow pressure of a compressible gas flowing from `P1` to `Pcf` in a tube of length L and friction factor `fd` [Pa] Notes ----- Assumes isothermal flow. Developed based on the `isothermal_gas` model, using SymPy. The isothermal gas model is solved for maximum mass flow rate; any pressure drop under it is impossible due to the formation of a shock wave. Examples -------- >>> P_isothermal_critical_flow(P=1E6, fd=0.00185, L=1000., D=0.5) 389699.7317645518 References ---------- .. [1] Wilkes, James O. Fluid Mechanics for Chemical Engineers with Microfluidics and CFD. 2 edition. Upper Saddle River, NJ: Prentice Hall, 2005.
[ "r", "Calculates", "critical", "flow", "pressure", "Pcf", "for", "a", "fluid", "flowing", "isothermally", "and", "suffering", "pressure", "drop", "caused", "by", "a", "pipe", "s", "friction", "factor", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L452-L499
8,260
CalebBell/fluids
fluids/compressible.py
P_upstream_isothermal_critical_flow
def P_upstream_isothermal_critical_flow(P, fd, D, L): '''Not part of the public API. Reverses `P_isothermal_critical_flow`. Examples -------- >>> P_upstream_isothermal_critical_flow(P=389699.7317645518, fd=0.00185, ... L=1000., D=0.5) 1000000.0000000001 ''' lambertw_term = float(lambertw(-exp(-(fd*L+D)/D), -1).real) return exp(-0.5*(D*lambertw_term+fd*L+D)/D)*P
python
def P_upstream_isothermal_critical_flow(P, fd, D, L): '''Not part of the public API. Reverses `P_isothermal_critical_flow`. Examples -------- >>> P_upstream_isothermal_critical_flow(P=389699.7317645518, fd=0.00185, ... L=1000., D=0.5) 1000000.0000000001 ''' lambertw_term = float(lambertw(-exp(-(fd*L+D)/D), -1).real) return exp(-0.5*(D*lambertw_term+fd*L+D)/D)*P
[ "def", "P_upstream_isothermal_critical_flow", "(", "P", ",", "fd", ",", "D", ",", "L", ")", ":", "lambertw_term", "=", "float", "(", "lambertw", "(", "-", "exp", "(", "-", "(", "fd", "*", "L", "+", "D", ")", "/", "D", ")", ",", "-", "1", ")", ".", "real", ")", "return", "exp", "(", "-", "0.5", "*", "(", "D", "*", "lambertw_term", "+", "fd", "*", "L", "+", "D", ")", "/", "D", ")", "*", "P" ]
Not part of the public API. Reverses `P_isothermal_critical_flow`. Examples -------- >>> P_upstream_isothermal_critical_flow(P=389699.7317645518, fd=0.00185, ... L=1000., D=0.5) 1000000.0000000001
[ "Not", "part", "of", "the", "public", "API", ".", "Reverses", "P_isothermal_critical_flow", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L502-L512
8,261
CalebBell/fluids
fluids/compressible.py
is_critical_flow
def is_critical_flow(P1, P2, k): r'''Determines if a flow of a fluid driven by pressure gradient P1 - P2 is critical, for a fluid with the given isentropic coefficient. This function calculates critical flow pressure, and checks if this is larger than P2. If so, the flow is critical and choked. Parameters ---------- P1 : float Higher, source pressure [Pa] P2 : float Lower, downstream pressure [Pa] k : float Isentropic coefficient [] Returns ------- flowtype : bool True if the flow is choked; otherwise False Notes ----- Assumes isentropic flow. Uses P_critical_flow function. Examples -------- Examples 1-2 from API 520. >>> is_critical_flow(670E3, 532E3, 1.11) False >>> is_critical_flow(670E3, 101E3, 1.11) True References ---------- .. [1] API. 2014. API 520 - Part 1 Sizing, Selection, and Installation of Pressure-relieving Devices, Part I - Sizing and Selection, 9E. ''' Pcf = P_critical_flow(P1, k) return Pcf > P2
python
def is_critical_flow(P1, P2, k): r'''Determines if a flow of a fluid driven by pressure gradient P1 - P2 is critical, for a fluid with the given isentropic coefficient. This function calculates critical flow pressure, and checks if this is larger than P2. If so, the flow is critical and choked. Parameters ---------- P1 : float Higher, source pressure [Pa] P2 : float Lower, downstream pressure [Pa] k : float Isentropic coefficient [] Returns ------- flowtype : bool True if the flow is choked; otherwise False Notes ----- Assumes isentropic flow. Uses P_critical_flow function. Examples -------- Examples 1-2 from API 520. >>> is_critical_flow(670E3, 532E3, 1.11) False >>> is_critical_flow(670E3, 101E3, 1.11) True References ---------- .. [1] API. 2014. API 520 - Part 1 Sizing, Selection, and Installation of Pressure-relieving Devices, Part I - Sizing and Selection, 9E. ''' Pcf = P_critical_flow(P1, k) return Pcf > P2
[ "def", "is_critical_flow", "(", "P1", ",", "P2", ",", "k", ")", ":", "Pcf", "=", "P_critical_flow", "(", "P1", ",", "k", ")", "return", "Pcf", ">", "P2" ]
r'''Determines if a flow of a fluid driven by pressure gradient P1 - P2 is critical, for a fluid with the given isentropic coefficient. This function calculates critical flow pressure, and checks if this is larger than P2. If so, the flow is critical and choked. Parameters ---------- P1 : float Higher, source pressure [Pa] P2 : float Lower, downstream pressure [Pa] k : float Isentropic coefficient [] Returns ------- flowtype : bool True if the flow is choked; otherwise False Notes ----- Assumes isentropic flow. Uses P_critical_flow function. Examples -------- Examples 1-2 from API 520. >>> is_critical_flow(670E3, 532E3, 1.11) False >>> is_critical_flow(670E3, 101E3, 1.11) True References ---------- .. [1] API. 2014. API 520 - Part 1 Sizing, Selection, and Installation of Pressure-relieving Devices, Part I - Sizing and Selection, 9E.
[ "r", "Determines", "if", "a", "flow", "of", "a", "fluid", "driven", "by", "pressure", "gradient", "P1", "-", "P2", "is", "critical", "for", "a", "fluid", "with", "the", "given", "isentropic", "coefficient", ".", "This", "function", "calculates", "critical", "flow", "pressure", "and", "checks", "if", "this", "is", "larger", "than", "P2", ".", "If", "so", "the", "flow", "is", "critical", "and", "choked", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L515-L554
8,262
CalebBell/fluids
fluids/friction.py
one_phase_dP
def one_phase_dP(m, rho, mu, D, roughness=0, L=1, Method=None): r'''Calculates single-phase pressure drop. This is a wrapper around other methods. Parameters ---------- m : float Mass flow rate of fluid, [kg/s] rho : float Density of fluid, [kg/m^3] mu : float Viscosity of fluid, [Pa*s] D : float Diameter of pipe, [m] roughness : float, optional Roughness of pipe for use in calculating friction factor, [m] L : float, optional Length of pipe, [m] Method : string, optional A string of the function name to use Returns ------- dP : float Pressure drop of the single-phase flow, [Pa] Notes ----- Examples -------- >>> one_phase_dP(10.0, 1000, 1E-5, .1, L=1) 63.43447321097365 References ---------- .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane, 2009. ''' D2 = D*D V = m/(0.25*pi*D2*rho) Re = Reynolds(V=V, rho=rho, mu=mu, D=D) fd = friction_factor(Re=Re, eD=roughness/D, Method=Method) dP = fd*L/D*(0.5*rho*V*V) return dP
python
def one_phase_dP(m, rho, mu, D, roughness=0, L=1, Method=None): r'''Calculates single-phase pressure drop. This is a wrapper around other methods. Parameters ---------- m : float Mass flow rate of fluid, [kg/s] rho : float Density of fluid, [kg/m^3] mu : float Viscosity of fluid, [Pa*s] D : float Diameter of pipe, [m] roughness : float, optional Roughness of pipe for use in calculating friction factor, [m] L : float, optional Length of pipe, [m] Method : string, optional A string of the function name to use Returns ------- dP : float Pressure drop of the single-phase flow, [Pa] Notes ----- Examples -------- >>> one_phase_dP(10.0, 1000, 1E-5, .1, L=1) 63.43447321097365 References ---------- .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane, 2009. ''' D2 = D*D V = m/(0.25*pi*D2*rho) Re = Reynolds(V=V, rho=rho, mu=mu, D=D) fd = friction_factor(Re=Re, eD=roughness/D, Method=Method) dP = fd*L/D*(0.5*rho*V*V) return dP
[ "def", "one_phase_dP", "(", "m", ",", "rho", ",", "mu", ",", "D", ",", "roughness", "=", "0", ",", "L", "=", "1", ",", "Method", "=", "None", ")", ":", "D2", "=", "D", "*", "D", "V", "=", "m", "/", "(", "0.25", "*", "pi", "*", "D2", "*", "rho", ")", "Re", "=", "Reynolds", "(", "V", "=", "V", ",", "rho", "=", "rho", ",", "mu", "=", "mu", ",", "D", "=", "D", ")", "fd", "=", "friction_factor", "(", "Re", "=", "Re", ",", "eD", "=", "roughness", "/", "D", ",", "Method", "=", "Method", ")", "dP", "=", "fd", "*", "L", "/", "D", "*", "(", "0.5", "*", "rho", "*", "V", "*", "V", ")", "return", "dP" ]
r'''Calculates single-phase pressure drop. This is a wrapper around other methods. Parameters ---------- m : float Mass flow rate of fluid, [kg/s] rho : float Density of fluid, [kg/m^3] mu : float Viscosity of fluid, [Pa*s] D : float Diameter of pipe, [m] roughness : float, optional Roughness of pipe for use in calculating friction factor, [m] L : float, optional Length of pipe, [m] Method : string, optional A string of the function name to use Returns ------- dP : float Pressure drop of the single-phase flow, [Pa] Notes ----- Examples -------- >>> one_phase_dP(10.0, 1000, 1E-5, .1, L=1) 63.43447321097365 References ---------- .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane, 2009.
[ "r", "Calculates", "single", "-", "phase", "pressure", "drop", ".", "This", "is", "a", "wrapper", "around", "other", "methods", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/friction.py#L3874-L3918
8,263
CalebBell/fluids
fluids/flow_meter.py
discharge_coefficient_to_K
def discharge_coefficient_to_K(D, Do, C): r'''Converts a discharge coefficient to a standard loss coefficient, for use in computation of the actual pressure drop of an orifice or other device. .. math:: K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2 Parameters ---------- D : float Upstream internal pipe diameter, [m] Do : float Diameter of orifice at flow conditions, [m] C : float Coefficient of discharge of the orifice, [-] Returns ------- K : float Loss coefficient with respect to the velocity and density of the fluid just upstream of the orifice, [-] Notes ----- If expansibility is used in the orifice calculation, the result will not match with the specified pressure drop formula in [1]_; it can almost be matched by dividing the calculated mass flow by the expansibility factor and using that mass flow with the loss coefficient. Examples -------- >>> discharge_coefficient_to_K(D=0.07366, Do=0.05, C=0.61512) 5.2314291729754 References ---------- .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001. .. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure Differential Devices Inserted in Circular Cross-Section Conduits Running Full -- Part 2: Orifice Plates. ''' beta = Do/D beta2 = beta*beta beta4 = beta2*beta2 return ((1.0 - beta4*(1.0 - C*C))**0.5/(C*beta2) - 1.0)**2
python
def discharge_coefficient_to_K(D, Do, C): r'''Converts a discharge coefficient to a standard loss coefficient, for use in computation of the actual pressure drop of an orifice or other device. .. math:: K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2 Parameters ---------- D : float Upstream internal pipe diameter, [m] Do : float Diameter of orifice at flow conditions, [m] C : float Coefficient of discharge of the orifice, [-] Returns ------- K : float Loss coefficient with respect to the velocity and density of the fluid just upstream of the orifice, [-] Notes ----- If expansibility is used in the orifice calculation, the result will not match with the specified pressure drop formula in [1]_; it can almost be matched by dividing the calculated mass flow by the expansibility factor and using that mass flow with the loss coefficient. Examples -------- >>> discharge_coefficient_to_K(D=0.07366, Do=0.05, C=0.61512) 5.2314291729754 References ---------- .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001. .. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure Differential Devices Inserted in Circular Cross-Section Conduits Running Full -- Part 2: Orifice Plates. ''' beta = Do/D beta2 = beta*beta beta4 = beta2*beta2 return ((1.0 - beta4*(1.0 - C*C))**0.5/(C*beta2) - 1.0)**2
[ "def", "discharge_coefficient_to_K", "(", "D", ",", "Do", ",", "C", ")", ":", "beta", "=", "Do", "/", "D", "beta2", "=", "beta", "*", "beta", "beta4", "=", "beta2", "*", "beta2", "return", "(", "(", "1.0", "-", "beta4", "*", "(", "1.0", "-", "C", "*", "C", ")", ")", "**", "0.5", "/", "(", "C", "*", "beta2", ")", "-", "1.0", ")", "**", "2" ]
r'''Converts a discharge coefficient to a standard loss coefficient, for use in computation of the actual pressure drop of an orifice or other device. .. math:: K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2 Parameters ---------- D : float Upstream internal pipe diameter, [m] Do : float Diameter of orifice at flow conditions, [m] C : float Coefficient of discharge of the orifice, [-] Returns ------- K : float Loss coefficient with respect to the velocity and density of the fluid just upstream of the orifice, [-] Notes ----- If expansibility is used in the orifice calculation, the result will not match with the specified pressure drop formula in [1]_; it can almost be matched by dividing the calculated mass flow by the expansibility factor and using that mass flow with the loss coefficient. Examples -------- >>> discharge_coefficient_to_K(D=0.07366, Do=0.05, C=0.61512) 5.2314291729754 References ---------- .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001. .. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure Differential Devices Inserted in Circular Cross-Section Conduits Running Full -- Part 2: Orifice Plates.
[ "r", "Converts", "a", "discharge", "coefficient", "to", "a", "standard", "loss", "coefficient", "for", "use", "in", "computation", "of", "the", "actual", "pressure", "drop", "of", "an", "orifice", "or", "other", "device", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/flow_meter.py#L438-L484
8,264
CalebBell/fluids
fluids/particle_size_distribution.py
ParticleSizeDistributionContinuous.dn
def dn(self, fraction, n=None): r'''Computes the diameter at which a specified `fraction` of the distribution falls under. Utilizes a bounded solver to search for the desired diameter. Parameters ---------- fraction : float Fraction of the distribution which should be under the calculated diameter, [-] n : int, optional None (for the `order` specified when the distribution was created), 0 (number), 1 (length), 2 (area), 3 (volume/mass), or any integer, [-] Returns ------- d : float Particle size diameter, [m] Examples -------- >>> psd = PSDLognormal(s=0.5, d_characteristic=5E-6, order=3) >>> psd.dn(.5) 5e-06 >>> psd.dn(1) 0.00029474365335233776 >>> psd.dn(0) 0.0 ''' if fraction == 1.0: # Avoid returning the maximum value of the search interval fraction = 1.0 - epsilon if fraction < 0: raise ValueError('Fraction must be more than 0') elif fraction == 0: # pragma: no cover if self.truncated: return self.d_min return 0.0 # Solve to float prevision limit - works well, but is there a real # point when with mpmath it would never happen? # dist.cdf(dist.dn(0)-1e-35) == 0 # dist.cdf(dist.dn(0)-1e-36) == input # dn(0) == 1.9663615597466143e-20 # def err(d): # cdf = self.cdf(d, n=n) # if cdf == 0: # cdf = -1 # return cdf # return brenth(err, self.d_minimum, self.d_excessive, maxiter=1000, xtol=1E-200) elif fraction > 1: raise ValueError('Fraction less than 1') # As the dn may be incredibly small, it is required for the absolute # tolerance to not be happy - it needs to continue iterating as long # as necessary to pin down the answer return brenth(lambda d:self.cdf(d, n=n) -fraction, self.d_minimum, self.d_excessive, maxiter=1000, xtol=1E-200)
python
def dn(self, fraction, n=None): r'''Computes the diameter at which a specified `fraction` of the distribution falls under. Utilizes a bounded solver to search for the desired diameter. Parameters ---------- fraction : float Fraction of the distribution which should be under the calculated diameter, [-] n : int, optional None (for the `order` specified when the distribution was created), 0 (number), 1 (length), 2 (area), 3 (volume/mass), or any integer, [-] Returns ------- d : float Particle size diameter, [m] Examples -------- >>> psd = PSDLognormal(s=0.5, d_characteristic=5E-6, order=3) >>> psd.dn(.5) 5e-06 >>> psd.dn(1) 0.00029474365335233776 >>> psd.dn(0) 0.0 ''' if fraction == 1.0: # Avoid returning the maximum value of the search interval fraction = 1.0 - epsilon if fraction < 0: raise ValueError('Fraction must be more than 0') elif fraction == 0: # pragma: no cover if self.truncated: return self.d_min return 0.0 # Solve to float prevision limit - works well, but is there a real # point when with mpmath it would never happen? # dist.cdf(dist.dn(0)-1e-35) == 0 # dist.cdf(dist.dn(0)-1e-36) == input # dn(0) == 1.9663615597466143e-20 # def err(d): # cdf = self.cdf(d, n=n) # if cdf == 0: # cdf = -1 # return cdf # return brenth(err, self.d_minimum, self.d_excessive, maxiter=1000, xtol=1E-200) elif fraction > 1: raise ValueError('Fraction less than 1') # As the dn may be incredibly small, it is required for the absolute # tolerance to not be happy - it needs to continue iterating as long # as necessary to pin down the answer return brenth(lambda d:self.cdf(d, n=n) -fraction, self.d_minimum, self.d_excessive, maxiter=1000, xtol=1E-200)
[ "def", "dn", "(", "self", ",", "fraction", ",", "n", "=", "None", ")", ":", "if", "fraction", "==", "1.0", ":", "# Avoid returning the maximum value of the search interval", "fraction", "=", "1.0", "-", "epsilon", "if", "fraction", "<", "0", ":", "raise", "ValueError", "(", "'Fraction must be more than 0'", ")", "elif", "fraction", "==", "0", ":", "# pragma: no cover", "if", "self", ".", "truncated", ":", "return", "self", ".", "d_min", "return", "0.0", "# Solve to float prevision limit - works well, but is there a real", "# point when with mpmath it would never happen?", "# dist.cdf(dist.dn(0)-1e-35) == 0", "# dist.cdf(dist.dn(0)-1e-36) == input", "# dn(0) == 1.9663615597466143e-20", "# def err(d): ", "# cdf = self.cdf(d, n=n)", "# if cdf == 0:", "# cdf = -1", "# return cdf", "# return brenth(err, self.d_minimum, self.d_excessive, maxiter=1000, xtol=1E-200)", "elif", "fraction", ">", "1", ":", "raise", "ValueError", "(", "'Fraction less than 1'", ")", "# As the dn may be incredibly small, it is required for the absolute ", "# tolerance to not be happy - it needs to continue iterating as long", "# as necessary to pin down the answer", "return", "brenth", "(", "lambda", "d", ":", "self", ".", "cdf", "(", "d", ",", "n", "=", "n", ")", "-", "fraction", ",", "self", ".", "d_minimum", ",", "self", ".", "d_excessive", ",", "maxiter", "=", "1000", ",", "xtol", "=", "1E-200", ")" ]
r'''Computes the diameter at which a specified `fraction` of the distribution falls under. Utilizes a bounded solver to search for the desired diameter. Parameters ---------- fraction : float Fraction of the distribution which should be under the calculated diameter, [-] n : int, optional None (for the `order` specified when the distribution was created), 0 (number), 1 (length), 2 (area), 3 (volume/mass), or any integer, [-] Returns ------- d : float Particle size diameter, [m] Examples -------- >>> psd = PSDLognormal(s=0.5, d_characteristic=5E-6, order=3) >>> psd.dn(.5) 5e-06 >>> psd.dn(1) 0.00029474365335233776 >>> psd.dn(0) 0.0
[ "r", "Computes", "the", "diameter", "at", "which", "a", "specified", "fraction", "of", "the", "distribution", "falls", "under", ".", "Utilizes", "a", "bounded", "solver", "to", "search", "for", "the", "desired", "diameter", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/particle_size_distribution.py#L1360-L1417
8,265
CalebBell/fluids
fluids/particle_size_distribution.py
ParticleSizeDistribution.fit
def fit(self, x0=None, distribution='lognormal', n=None, **kwargs): '''Incomplete method to fit experimental values to a curve. It is very hard to get good initial guesses, which are really required for this. Differential evolution is promissing. This API is likely to change in the future. ''' dist = {'lognormal': PSDLognormal, 'GGS': PSDGatesGaudinSchuhman, 'RR': PSDRosinRammler}[distribution] if distribution == 'lognormal': if x0 is None: d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)]) s = 0.4 x0 = [d_characteristic, s] elif distribution == 'GGS': if x0 is None: d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)]) m = 1.5 x0 = [d_characteristic, m] elif distribution == 'RR': if x0 is None: x0 = [5E-6, 1e-2] from scipy.optimize import minimize return minimize(self._fit_obj_function, x0, args=(dist, n), **kwargs)
python
def fit(self, x0=None, distribution='lognormal', n=None, **kwargs): '''Incomplete method to fit experimental values to a curve. It is very hard to get good initial guesses, which are really required for this. Differential evolution is promissing. This API is likely to change in the future. ''' dist = {'lognormal': PSDLognormal, 'GGS': PSDGatesGaudinSchuhman, 'RR': PSDRosinRammler}[distribution] if distribution == 'lognormal': if x0 is None: d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)]) s = 0.4 x0 = [d_characteristic, s] elif distribution == 'GGS': if x0 is None: d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)]) m = 1.5 x0 = [d_characteristic, m] elif distribution == 'RR': if x0 is None: x0 = [5E-6, 1e-2] from scipy.optimize import minimize return minimize(self._fit_obj_function, x0, args=(dist, n), **kwargs)
[ "def", "fit", "(", "self", ",", "x0", "=", "None", ",", "distribution", "=", "'lognormal'", ",", "n", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dist", "=", "{", "'lognormal'", ":", "PSDLognormal", ",", "'GGS'", ":", "PSDGatesGaudinSchuhman", ",", "'RR'", ":", "PSDRosinRammler", "}", "[", "distribution", "]", "if", "distribution", "==", "'lognormal'", ":", "if", "x0", "is", "None", ":", "d_characteristic", "=", "sum", "(", "[", "fi", "*", "di", "for", "fi", ",", "di", "in", "zip", "(", "self", ".", "fractions", ",", "self", ".", "Dis", ")", "]", ")", "s", "=", "0.4", "x0", "=", "[", "d_characteristic", ",", "s", "]", "elif", "distribution", "==", "'GGS'", ":", "if", "x0", "is", "None", ":", "d_characteristic", "=", "sum", "(", "[", "fi", "*", "di", "for", "fi", ",", "di", "in", "zip", "(", "self", ".", "fractions", ",", "self", ".", "Dis", ")", "]", ")", "m", "=", "1.5", "x0", "=", "[", "d_characteristic", ",", "m", "]", "elif", "distribution", "==", "'RR'", ":", "if", "x0", "is", "None", ":", "x0", "=", "[", "5E-6", ",", "1e-2", "]", "from", "scipy", ".", "optimize", "import", "minimize", "return", "minimize", "(", "self", ".", "_fit_obj_function", ",", "x0", ",", "args", "=", "(", "dist", ",", "n", ")", ",", "*", "*", "kwargs", ")" ]
Incomplete method to fit experimental values to a curve. It is very hard to get good initial guesses, which are really required for this. Differential evolution is promissing. This API is likely to change in the future.
[ "Incomplete", "method", "to", "fit", "experimental", "values", "to", "a", "curve", ".", "It", "is", "very", "hard", "to", "get", "good", "initial", "guesses", "which", "are", "really", "required", "for", "this", ".", "Differential", "evolution", "is", "promissing", ".", "This", "API", "is", "likely", "to", "change", "in", "the", "future", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/particle_size_distribution.py#L1881-L1905
8,266
CalebBell/fluids
fluids/particle_size_distribution.py
ParticleSizeDistribution.Dis
def Dis(self): '''Representative diameters of each bin. ''' return [self.di_power(i, power=1) for i in range(self.N)]
python
def Dis(self): '''Representative diameters of each bin. ''' return [self.di_power(i, power=1) for i in range(self.N)]
[ "def", "Dis", "(", "self", ")", ":", "return", "[", "self", ".", "di_power", "(", "i", ",", "power", "=", "1", ")", "for", "i", "in", "range", "(", "self", ".", "N", ")", "]" ]
Representative diameters of each bin.
[ "Representative", "diameters", "of", "each", "bin", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/particle_size_distribution.py#L1908-L1911
8,267
CalebBell/fluids
fluids/geometry.py
SA_tank
def SA_tank(D, L, sideA=None, sideB=None, sideA_a=0, sideB_a=0, sideA_f=None, sideA_k=None, sideB_f=None, sideB_k=None, full_output=False): r'''Calculates the surface are of a cylindrical tank with optional heads. In the degenerate case of being provided with only `D` and `L`, provides the surface area of a cylinder. Parameters ---------- D : float Diameter of the cylindrical section of the tank, [m] L : float Length of the main cylindrical section of the tank, [m] sideA : string, optional The left (or bottom for vertical) head of the tank's type; one of [None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical']. sideB : string, optional The right (or top for vertical) head of the tank's type; one of [None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical']. sideA_a : float, optional The distance the head as specified by sideA extends down or to the left from the main cylindrical section, [m] sideB_a : float, optional The distance the head as specified by sideB extends up or to the right from the main cylindrical section, [m] sideA_f : float, optional Dish-radius parameter for side A; fD = dish radius [1/m] sideA_k : float, optional knuckle-radius parameter for side A; kD = knuckle radius [1/m] sideB_f : float, optional Dish-radius parameter for side B; fD = dish radius [1/m] sideB_k : float, optional knuckle-radius parameter for side B; kD = knuckle radius [1/m] Returns ------- SA : float Surface area of the tank [m^2] areas : tuple, only returned if full_output == True (sideA_SA, sideB_SA, lateral_SA) Other Parameters ---------------- full_output : bool, optional Returns a tuple of (sideA_SA, sideB_SA, lateral_SA) if True Examples -------- Cylinder, Spheroid, Long Cones, and spheres. All checked. >>> SA_tank(D=2, L=2) 18.84955592153876 >>> SA_tank(D=1., L=0, sideA='ellipsoidal', sideA_a=2, sideB='ellipsoidal', ... sideB_a=2) 28.480278854014387 >>> SA_tank(D=1., L=5, sideA='conical', sideA_a=2, sideB='conical', ... sideB_a=2) 22.18452243965656 >>> SA_tank(D=1., L=5, sideA='spherical', sideA_a=0.5, sideB='spherical', ... sideB_a=0.5) 18.84955592153876 ''' # Side A if sideA == 'conical': sideA_SA = SA_conical_head(D=D, a=sideA_a) elif sideA == 'ellipsoidal': sideA_SA = SA_ellipsoidal_head(D=D, a=sideA_a) elif sideA == 'guppy': sideA_SA = SA_guppy_head(D=D, a=sideA_a) elif sideA == 'spherical': sideA_SA = SA_partial_sphere(D=D, h=sideA_a) elif sideA == 'torispherical': sideA_SA = SA_torispheroidal(D=D, fd=sideA_f, fk=sideA_k) else: sideA_SA = pi/4*D**2 # Circle # Side B if sideB == 'conical': sideB_SA = SA_conical_head(D=D, a=sideB_a) elif sideB == 'ellipsoidal': sideB_SA = SA_ellipsoidal_head(D=D, a=sideB_a) elif sideB == 'guppy': sideB_SA = SA_guppy_head(D=D, a=sideB_a) elif sideB == 'spherical': sideB_SA = SA_partial_sphere(D=D, h=sideB_a) elif sideB == 'torispherical': sideB_SA = SA_torispheroidal(D=D, fd=sideB_f, fk=sideB_k) else: sideB_SA = pi/4*D**2 # Circle lateral_SA = pi*D*L SA = sideA_SA + sideB_SA + lateral_SA if full_output: return SA, (sideA_SA, sideB_SA, lateral_SA) else: return SA
python
def SA_tank(D, L, sideA=None, sideB=None, sideA_a=0, sideB_a=0, sideA_f=None, sideA_k=None, sideB_f=None, sideB_k=None, full_output=False): r'''Calculates the surface are of a cylindrical tank with optional heads. In the degenerate case of being provided with only `D` and `L`, provides the surface area of a cylinder. Parameters ---------- D : float Diameter of the cylindrical section of the tank, [m] L : float Length of the main cylindrical section of the tank, [m] sideA : string, optional The left (or bottom for vertical) head of the tank's type; one of [None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical']. sideB : string, optional The right (or top for vertical) head of the tank's type; one of [None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical']. sideA_a : float, optional The distance the head as specified by sideA extends down or to the left from the main cylindrical section, [m] sideB_a : float, optional The distance the head as specified by sideB extends up or to the right from the main cylindrical section, [m] sideA_f : float, optional Dish-radius parameter for side A; fD = dish radius [1/m] sideA_k : float, optional knuckle-radius parameter for side A; kD = knuckle radius [1/m] sideB_f : float, optional Dish-radius parameter for side B; fD = dish radius [1/m] sideB_k : float, optional knuckle-radius parameter for side B; kD = knuckle radius [1/m] Returns ------- SA : float Surface area of the tank [m^2] areas : tuple, only returned if full_output == True (sideA_SA, sideB_SA, lateral_SA) Other Parameters ---------------- full_output : bool, optional Returns a tuple of (sideA_SA, sideB_SA, lateral_SA) if True Examples -------- Cylinder, Spheroid, Long Cones, and spheres. All checked. >>> SA_tank(D=2, L=2) 18.84955592153876 >>> SA_tank(D=1., L=0, sideA='ellipsoidal', sideA_a=2, sideB='ellipsoidal', ... sideB_a=2) 28.480278854014387 >>> SA_tank(D=1., L=5, sideA='conical', sideA_a=2, sideB='conical', ... sideB_a=2) 22.18452243965656 >>> SA_tank(D=1., L=5, sideA='spherical', sideA_a=0.5, sideB='spherical', ... sideB_a=0.5) 18.84955592153876 ''' # Side A if sideA == 'conical': sideA_SA = SA_conical_head(D=D, a=sideA_a) elif sideA == 'ellipsoidal': sideA_SA = SA_ellipsoidal_head(D=D, a=sideA_a) elif sideA == 'guppy': sideA_SA = SA_guppy_head(D=D, a=sideA_a) elif sideA == 'spherical': sideA_SA = SA_partial_sphere(D=D, h=sideA_a) elif sideA == 'torispherical': sideA_SA = SA_torispheroidal(D=D, fd=sideA_f, fk=sideA_k) else: sideA_SA = pi/4*D**2 # Circle # Side B if sideB == 'conical': sideB_SA = SA_conical_head(D=D, a=sideB_a) elif sideB == 'ellipsoidal': sideB_SA = SA_ellipsoidal_head(D=D, a=sideB_a) elif sideB == 'guppy': sideB_SA = SA_guppy_head(D=D, a=sideB_a) elif sideB == 'spherical': sideB_SA = SA_partial_sphere(D=D, h=sideB_a) elif sideB == 'torispherical': sideB_SA = SA_torispheroidal(D=D, fd=sideB_f, fk=sideB_k) else: sideB_SA = pi/4*D**2 # Circle lateral_SA = pi*D*L SA = sideA_SA + sideB_SA + lateral_SA if full_output: return SA, (sideA_SA, sideB_SA, lateral_SA) else: return SA
[ "def", "SA_tank", "(", "D", ",", "L", ",", "sideA", "=", "None", ",", "sideB", "=", "None", ",", "sideA_a", "=", "0", ",", "sideB_a", "=", "0", ",", "sideA_f", "=", "None", ",", "sideA_k", "=", "None", ",", "sideB_f", "=", "None", ",", "sideB_k", "=", "None", ",", "full_output", "=", "False", ")", ":", "# Side A", "if", "sideA", "==", "'conical'", ":", "sideA_SA", "=", "SA_conical_head", "(", "D", "=", "D", ",", "a", "=", "sideA_a", ")", "elif", "sideA", "==", "'ellipsoidal'", ":", "sideA_SA", "=", "SA_ellipsoidal_head", "(", "D", "=", "D", ",", "a", "=", "sideA_a", ")", "elif", "sideA", "==", "'guppy'", ":", "sideA_SA", "=", "SA_guppy_head", "(", "D", "=", "D", ",", "a", "=", "sideA_a", ")", "elif", "sideA", "==", "'spherical'", ":", "sideA_SA", "=", "SA_partial_sphere", "(", "D", "=", "D", ",", "h", "=", "sideA_a", ")", "elif", "sideA", "==", "'torispherical'", ":", "sideA_SA", "=", "SA_torispheroidal", "(", "D", "=", "D", ",", "fd", "=", "sideA_f", ",", "fk", "=", "sideA_k", ")", "else", ":", "sideA_SA", "=", "pi", "/", "4", "*", "D", "**", "2", "# Circle", "# Side B", "if", "sideB", "==", "'conical'", ":", "sideB_SA", "=", "SA_conical_head", "(", "D", "=", "D", ",", "a", "=", "sideB_a", ")", "elif", "sideB", "==", "'ellipsoidal'", ":", "sideB_SA", "=", "SA_ellipsoidal_head", "(", "D", "=", "D", ",", "a", "=", "sideB_a", ")", "elif", "sideB", "==", "'guppy'", ":", "sideB_SA", "=", "SA_guppy_head", "(", "D", "=", "D", ",", "a", "=", "sideB_a", ")", "elif", "sideB", "==", "'spherical'", ":", "sideB_SA", "=", "SA_partial_sphere", "(", "D", "=", "D", ",", "h", "=", "sideB_a", ")", "elif", "sideB", "==", "'torispherical'", ":", "sideB_SA", "=", "SA_torispheroidal", "(", "D", "=", "D", ",", "fd", "=", "sideB_f", ",", "fk", "=", "sideB_k", ")", "else", ":", "sideB_SA", "=", "pi", "/", "4", "*", "D", "**", "2", "# Circle", "lateral_SA", "=", "pi", "*", "D", "*", "L", "SA", "=", "sideA_SA", "+", "sideB_SA", "+", "lateral_SA", "if", "full_output", ":", "return", "SA", ",", "(", "sideA_SA", ",", "sideB_SA", ",", "lateral_SA", ")", "else", ":", "return", "SA" ]
r'''Calculates the surface are of a cylindrical tank with optional heads. In the degenerate case of being provided with only `D` and `L`, provides the surface area of a cylinder. Parameters ---------- D : float Diameter of the cylindrical section of the tank, [m] L : float Length of the main cylindrical section of the tank, [m] sideA : string, optional The left (or bottom for vertical) head of the tank's type; one of [None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical']. sideB : string, optional The right (or top for vertical) head of the tank's type; one of [None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical']. sideA_a : float, optional The distance the head as specified by sideA extends down or to the left from the main cylindrical section, [m] sideB_a : float, optional The distance the head as specified by sideB extends up or to the right from the main cylindrical section, [m] sideA_f : float, optional Dish-radius parameter for side A; fD = dish radius [1/m] sideA_k : float, optional knuckle-radius parameter for side A; kD = knuckle radius [1/m] sideB_f : float, optional Dish-radius parameter for side B; fD = dish radius [1/m] sideB_k : float, optional knuckle-radius parameter for side B; kD = knuckle radius [1/m] Returns ------- SA : float Surface area of the tank [m^2] areas : tuple, only returned if full_output == True (sideA_SA, sideB_SA, lateral_SA) Other Parameters ---------------- full_output : bool, optional Returns a tuple of (sideA_SA, sideB_SA, lateral_SA) if True Examples -------- Cylinder, Spheroid, Long Cones, and spheres. All checked. >>> SA_tank(D=2, L=2) 18.84955592153876 >>> SA_tank(D=1., L=0, sideA='ellipsoidal', sideA_a=2, sideB='ellipsoidal', ... sideB_a=2) 28.480278854014387 >>> SA_tank(D=1., L=5, sideA='conical', sideA_a=2, sideB='conical', ... sideB_a=2) 22.18452243965656 >>> SA_tank(D=1., L=5, sideA='spherical', sideA_a=0.5, sideB='spherical', ... sideB_a=0.5) 18.84955592153876
[ "r", "Calculates", "the", "surface", "are", "of", "a", "cylindrical", "tank", "with", "optional", "heads", ".", "In", "the", "degenerate", "case", "of", "being", "provided", "with", "only", "D", "and", "L", "provides", "the", "surface", "area", "of", "a", "cylinder", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1192-L1287
8,268
CalebBell/fluids
fluids/geometry.py
pitch_angle_solver
def pitch_angle_solver(angle=None, pitch=None, pitch_parallel=None, pitch_normal=None): r'''Utility to take any two of `angle`, `pitch`, `pitch_parallel`, and `pitch_normal` and calculate the other two. This is useful for applications with tube banks, as in shell and tube heat exchangers or air coolers and allows for a wider range of user input. .. math:: \text{pitch normal} = \text{pitch} \cdot \sin(\text{angle}) .. math:: \text{pitch parallel} = \text{pitch} \cdot \cos(\text{angle}) Parameters ---------- angle : float, optional The angle of the tube layout, [degrees] pitch : float, optional The shortest distance between tube centers; defined in relation to the flow direction only, [m] pitch_parallel : float, optional The distance between tube center along a line parallel to the flow; has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m] pitch_normal : float, optional The distance between tube centers in a line 90° to the line of flow; has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m] Returns ------- angle : float The angle of the tube layout, [degrees] pitch : float The shortest distance between tube centers; defined in relation to the flow direction only, [m] pitch_parallel : float The distance between tube center along a line parallel to the flow; has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m] pitch_normal : float The distance between tube centers in a line 90° to the line of flow; has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m] Notes ----- For the 90 and 0 degree case, the normal or parallel pitches can be zero; given the angle and the zero value, obviously is it not possible to calculate the pitch and a math error will be raised. No exception will be raised if three or four inputs are provided; the other two will simply be calculated according to the list of if statements used. An exception will be raised if only one input is provided. Examples -------- >>> pitch_angle_solver(pitch=1, angle=30) (30, 1, 0.8660254037844387, 0.49999999999999994) References ---------- .. [1] Schlunder, Ernst U, and International Center for Heat and Mass Transfer. Heat Exchanger Design Handbook. Washington: Hemisphere Pub. Corp., 1983. ''' if angle is not None and pitch is not None: pitch_normal = pitch*sin(radians(angle)) pitch_parallel = pitch*cos(radians(angle)) elif angle is not None and pitch_normal is not None: pitch = pitch_normal/sin(radians(angle)) pitch_parallel = pitch*cos(radians(angle)) elif angle is not None and pitch_parallel is not None: pitch = pitch_parallel/cos(radians(angle)) pitch_normal = pitch*sin(radians(angle)) elif pitch_normal is not None and pitch is not None: angle = degrees(asin(pitch_normal/pitch)) pitch_parallel = pitch*cos(radians(angle)) elif pitch_parallel is not None and pitch is not None: angle = degrees(acos(pitch_parallel/pitch)) pitch_normal = pitch*sin(radians(angle)) elif pitch_parallel is not None and pitch_normal is not None: angle = degrees(asin(pitch_normal/(pitch_normal**2 + pitch_parallel**2)**0.5)) pitch = (pitch_normal**2 + pitch_parallel**2)**0.5 else: raise Exception('Two of the arguments are required') return angle, pitch, pitch_parallel, pitch_normal
python
def pitch_angle_solver(angle=None, pitch=None, pitch_parallel=None, pitch_normal=None): r'''Utility to take any two of `angle`, `pitch`, `pitch_parallel`, and `pitch_normal` and calculate the other two. This is useful for applications with tube banks, as in shell and tube heat exchangers or air coolers and allows for a wider range of user input. .. math:: \text{pitch normal} = \text{pitch} \cdot \sin(\text{angle}) .. math:: \text{pitch parallel} = \text{pitch} \cdot \cos(\text{angle}) Parameters ---------- angle : float, optional The angle of the tube layout, [degrees] pitch : float, optional The shortest distance between tube centers; defined in relation to the flow direction only, [m] pitch_parallel : float, optional The distance between tube center along a line parallel to the flow; has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m] pitch_normal : float, optional The distance between tube centers in a line 90° to the line of flow; has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m] Returns ------- angle : float The angle of the tube layout, [degrees] pitch : float The shortest distance between tube centers; defined in relation to the flow direction only, [m] pitch_parallel : float The distance between tube center along a line parallel to the flow; has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m] pitch_normal : float The distance between tube centers in a line 90° to the line of flow; has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m] Notes ----- For the 90 and 0 degree case, the normal or parallel pitches can be zero; given the angle and the zero value, obviously is it not possible to calculate the pitch and a math error will be raised. No exception will be raised if three or four inputs are provided; the other two will simply be calculated according to the list of if statements used. An exception will be raised if only one input is provided. Examples -------- >>> pitch_angle_solver(pitch=1, angle=30) (30, 1, 0.8660254037844387, 0.49999999999999994) References ---------- .. [1] Schlunder, Ernst U, and International Center for Heat and Mass Transfer. Heat Exchanger Design Handbook. Washington: Hemisphere Pub. Corp., 1983. ''' if angle is not None and pitch is not None: pitch_normal = pitch*sin(radians(angle)) pitch_parallel = pitch*cos(radians(angle)) elif angle is not None and pitch_normal is not None: pitch = pitch_normal/sin(radians(angle)) pitch_parallel = pitch*cos(radians(angle)) elif angle is not None and pitch_parallel is not None: pitch = pitch_parallel/cos(radians(angle)) pitch_normal = pitch*sin(radians(angle)) elif pitch_normal is not None and pitch is not None: angle = degrees(asin(pitch_normal/pitch)) pitch_parallel = pitch*cos(radians(angle)) elif pitch_parallel is not None and pitch is not None: angle = degrees(acos(pitch_parallel/pitch)) pitch_normal = pitch*sin(radians(angle)) elif pitch_parallel is not None and pitch_normal is not None: angle = degrees(asin(pitch_normal/(pitch_normal**2 + pitch_parallel**2)**0.5)) pitch = (pitch_normal**2 + pitch_parallel**2)**0.5 else: raise Exception('Two of the arguments are required') return angle, pitch, pitch_parallel, pitch_normal
[ "def", "pitch_angle_solver", "(", "angle", "=", "None", ",", "pitch", "=", "None", ",", "pitch_parallel", "=", "None", ",", "pitch_normal", "=", "None", ")", ":", "if", "angle", "is", "not", "None", "and", "pitch", "is", "not", "None", ":", "pitch_normal", "=", "pitch", "*", "sin", "(", "radians", "(", "angle", ")", ")", "pitch_parallel", "=", "pitch", "*", "cos", "(", "radians", "(", "angle", ")", ")", "elif", "angle", "is", "not", "None", "and", "pitch_normal", "is", "not", "None", ":", "pitch", "=", "pitch_normal", "/", "sin", "(", "radians", "(", "angle", ")", ")", "pitch_parallel", "=", "pitch", "*", "cos", "(", "radians", "(", "angle", ")", ")", "elif", "angle", "is", "not", "None", "and", "pitch_parallel", "is", "not", "None", ":", "pitch", "=", "pitch_parallel", "/", "cos", "(", "radians", "(", "angle", ")", ")", "pitch_normal", "=", "pitch", "*", "sin", "(", "radians", "(", "angle", ")", ")", "elif", "pitch_normal", "is", "not", "None", "and", "pitch", "is", "not", "None", ":", "angle", "=", "degrees", "(", "asin", "(", "pitch_normal", "/", "pitch", ")", ")", "pitch_parallel", "=", "pitch", "*", "cos", "(", "radians", "(", "angle", ")", ")", "elif", "pitch_parallel", "is", "not", "None", "and", "pitch", "is", "not", "None", ":", "angle", "=", "degrees", "(", "acos", "(", "pitch_parallel", "/", "pitch", ")", ")", "pitch_normal", "=", "pitch", "*", "sin", "(", "radians", "(", "angle", ")", ")", "elif", "pitch_parallel", "is", "not", "None", "and", "pitch_normal", "is", "not", "None", ":", "angle", "=", "degrees", "(", "asin", "(", "pitch_normal", "/", "(", "pitch_normal", "**", "2", "+", "pitch_parallel", "**", "2", ")", "**", "0.5", ")", ")", "pitch", "=", "(", "pitch_normal", "**", "2", "+", "pitch_parallel", "**", "2", ")", "**", "0.5", "else", ":", "raise", "Exception", "(", "'Two of the arguments are required'", ")", "return", "angle", ",", "pitch", ",", "pitch_parallel", ",", "pitch_normal" ]
r'''Utility to take any two of `angle`, `pitch`, `pitch_parallel`, and `pitch_normal` and calculate the other two. This is useful for applications with tube banks, as in shell and tube heat exchangers or air coolers and allows for a wider range of user input. .. math:: \text{pitch normal} = \text{pitch} \cdot \sin(\text{angle}) .. math:: \text{pitch parallel} = \text{pitch} \cdot \cos(\text{angle}) Parameters ---------- angle : float, optional The angle of the tube layout, [degrees] pitch : float, optional The shortest distance between tube centers; defined in relation to the flow direction only, [m] pitch_parallel : float, optional The distance between tube center along a line parallel to the flow; has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m] pitch_normal : float, optional The distance between tube centers in a line 90° to the line of flow; has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m] Returns ------- angle : float The angle of the tube layout, [degrees] pitch : float The shortest distance between tube centers; defined in relation to the flow direction only, [m] pitch_parallel : float The distance between tube center along a line parallel to the flow; has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m] pitch_normal : float The distance between tube centers in a line 90° to the line of flow; has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m] Notes ----- For the 90 and 0 degree case, the normal or parallel pitches can be zero; given the angle and the zero value, obviously is it not possible to calculate the pitch and a math error will be raised. No exception will be raised if three or four inputs are provided; the other two will simply be calculated according to the list of if statements used. An exception will be raised if only one input is provided. Examples -------- >>> pitch_angle_solver(pitch=1, angle=30) (30, 1, 0.8660254037844387, 0.49999999999999994) References ---------- .. [1] Schlunder, Ernst U, and International Center for Heat and Mass Transfer. Heat Exchanger Design Handbook. Washington: Hemisphere Pub. Corp., 1983.
[ "r", "Utility", "to", "take", "any", "two", "of", "angle", "pitch", "pitch_parallel", "and", "pitch_normal", "and", "calculate", "the", "other", "two", ".", "This", "is", "useful", "for", "applications", "with", "tube", "banks", "as", "in", "shell", "and", "tube", "heat", "exchangers", "or", "air", "coolers", "and", "allows", "for", "a", "wider", "range", "of", "user", "input", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L3030-L3113
8,269
CalebBell/fluids
fluids/geometry.py
A_hollow_cylinder
def A_hollow_cylinder(Di, Do, L): r'''Returns the surface area of a hollow cylinder. .. math:: A = \pi D_o L + \pi D_i L + 2\cdot \frac{\pi D_o^2}{4} - 2\cdot \frac{\pi D_i^2}{4} Parameters ---------- Di : float Diameter of the hollow in the cylinder, [m] Do : float Diameter of the exterior of the cylinder, [m] L : float Length of the cylinder, [m] Returns ------- A : float Surface area [m^2] Examples -------- >>> A_hollow_cylinder(0.005, 0.01, 0.1) 0.004830198704894308 ''' side_o = pi*Do*L side_i = pi*Di*L cap_circle = pi*Do**2/4*2 cap_removed = pi*Di**2/4*2 return side_o + side_i + cap_circle - cap_removed
python
def A_hollow_cylinder(Di, Do, L): r'''Returns the surface area of a hollow cylinder. .. math:: A = \pi D_o L + \pi D_i L + 2\cdot \frac{\pi D_o^2}{4} - 2\cdot \frac{\pi D_i^2}{4} Parameters ---------- Di : float Diameter of the hollow in the cylinder, [m] Do : float Diameter of the exterior of the cylinder, [m] L : float Length of the cylinder, [m] Returns ------- A : float Surface area [m^2] Examples -------- >>> A_hollow_cylinder(0.005, 0.01, 0.1) 0.004830198704894308 ''' side_o = pi*Do*L side_i = pi*Di*L cap_circle = pi*Do**2/4*2 cap_removed = pi*Di**2/4*2 return side_o + side_i + cap_circle - cap_removed
[ "def", "A_hollow_cylinder", "(", "Di", ",", "Do", ",", "L", ")", ":", "side_o", "=", "pi", "*", "Do", "*", "L", "side_i", "=", "pi", "*", "Di", "*", "L", "cap_circle", "=", "pi", "*", "Do", "**", "2", "/", "4", "*", "2", "cap_removed", "=", "pi", "*", "Di", "**", "2", "/", "4", "*", "2", "return", "side_o", "+", "side_i", "+", "cap_circle", "-", "cap_removed" ]
r'''Returns the surface area of a hollow cylinder. .. math:: A = \pi D_o L + \pi D_i L + 2\cdot \frac{\pi D_o^2}{4} - 2\cdot \frac{\pi D_i^2}{4} Parameters ---------- Di : float Diameter of the hollow in the cylinder, [m] Do : float Diameter of the exterior of the cylinder, [m] L : float Length of the cylinder, [m] Returns ------- A : float Surface area [m^2] Examples -------- >>> A_hollow_cylinder(0.005, 0.01, 0.1) 0.004830198704894308
[ "r", "Returns", "the", "surface", "area", "of", "a", "hollow", "cylinder", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L3285-L3315
8,270
CalebBell/fluids
fluids/geometry.py
A_multiple_hole_cylinder
def A_multiple_hole_cylinder(Do, L, holes): r'''Returns the surface area of a cylinder with multiple holes. Calculation will naively return a negative value or other impossible result if the number of cylinders added is physically impossible. Holes may be of different shapes, but must be perpendicular to the axis of the cylinder. .. math:: A = \pi D_o L + 2\cdot \frac{\pi D_o^2}{4} + \sum_{i}^n \left( \pi D_i L - 2\cdot \frac{\pi D_i^2}{4}\right) Parameters ---------- Do : float Diameter of the exterior of the cylinder, [m] L : float Length of the cylinder, [m] holes : list List of tuples containing (diameter, count) pairs of descriptions for each of the holes sizes. Returns ------- A : float Surface area [m^2] Examples -------- >>> A_multiple_hole_cylinder(0.01, 0.1, [(0.005, 1)]) 0.004830198704894308 ''' side_o = pi*Do*L cap_circle = pi*Do**2/4*2 A = cap_circle + side_o for Di, n in holes: side_i = pi*Di*L cap_removed = pi*Di**2/4*2 A = A + side_i*n - cap_removed*n return A
python
def A_multiple_hole_cylinder(Do, L, holes): r'''Returns the surface area of a cylinder with multiple holes. Calculation will naively return a negative value or other impossible result if the number of cylinders added is physically impossible. Holes may be of different shapes, but must be perpendicular to the axis of the cylinder. .. math:: A = \pi D_o L + 2\cdot \frac{\pi D_o^2}{4} + \sum_{i}^n \left( \pi D_i L - 2\cdot \frac{\pi D_i^2}{4}\right) Parameters ---------- Do : float Diameter of the exterior of the cylinder, [m] L : float Length of the cylinder, [m] holes : list List of tuples containing (diameter, count) pairs of descriptions for each of the holes sizes. Returns ------- A : float Surface area [m^2] Examples -------- >>> A_multiple_hole_cylinder(0.01, 0.1, [(0.005, 1)]) 0.004830198704894308 ''' side_o = pi*Do*L cap_circle = pi*Do**2/4*2 A = cap_circle + side_o for Di, n in holes: side_i = pi*Di*L cap_removed = pi*Di**2/4*2 A = A + side_i*n - cap_removed*n return A
[ "def", "A_multiple_hole_cylinder", "(", "Do", ",", "L", ",", "holes", ")", ":", "side_o", "=", "pi", "*", "Do", "*", "L", "cap_circle", "=", "pi", "*", "Do", "**", "2", "/", "4", "*", "2", "A", "=", "cap_circle", "+", "side_o", "for", "Di", ",", "n", "in", "holes", ":", "side_i", "=", "pi", "*", "Di", "*", "L", "cap_removed", "=", "pi", "*", "Di", "**", "2", "/", "4", "*", "2", "A", "=", "A", "+", "side_i", "*", "n", "-", "cap_removed", "*", "n", "return", "A" ]
r'''Returns the surface area of a cylinder with multiple holes. Calculation will naively return a negative value or other impossible result if the number of cylinders added is physically impossible. Holes may be of different shapes, but must be perpendicular to the axis of the cylinder. .. math:: A = \pi D_o L + 2\cdot \frac{\pi D_o^2}{4} + \sum_{i}^n \left( \pi D_i L - 2\cdot \frac{\pi D_i^2}{4}\right) Parameters ---------- Do : float Diameter of the exterior of the cylinder, [m] L : float Length of the cylinder, [m] holes : list List of tuples containing (diameter, count) pairs of descriptions for each of the holes sizes. Returns ------- A : float Surface area [m^2] Examples -------- >>> A_multiple_hole_cylinder(0.01, 0.1, [(0.005, 1)]) 0.004830198704894308
[ "r", "Returns", "the", "surface", "area", "of", "a", "cylinder", "with", "multiple", "holes", ".", "Calculation", "will", "naively", "return", "a", "negative", "value", "or", "other", "impossible", "result", "if", "the", "number", "of", "cylinders", "added", "is", "physically", "impossible", ".", "Holes", "may", "be", "of", "different", "shapes", "but", "must", "be", "perpendicular", "to", "the", "axis", "of", "the", "cylinder", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L3346-L3384
8,271
CalebBell/fluids
fluids/geometry.py
TANK.V_from_h
def V_from_h(self, h, method='full'): r'''Method to calculate the volume of liquid in a fully defined tank given a specified height `h`. `h` must be under the maximum height. If the method is 'chebyshev', and the coefficients have not yet been calculated, they are created by calling `set_chebyshev_approximators`. Parameters ---------- h : float Height specified, [m] method : str One of 'full' (calculated rigorously) or 'chebyshev' Returns ------- V : float Volume of liquid in the tank up to the specified height, [m^3] Notes ----- ''' if method == 'full': return V_from_h(h, self.D, self.L, self.horizontal, self.sideA, self.sideB, self.sideA_a, self.sideB_a, self.sideA_f, self.sideA_k, self.sideB_f, self.sideB_k) elif method == 'chebyshev': if not self.chebyshev: self.set_chebyshev_approximators() return self.V_from_h_cheb(h) else: raise Exception("Allowable methods are 'full' or 'chebyshev'.")
python
def V_from_h(self, h, method='full'): r'''Method to calculate the volume of liquid in a fully defined tank given a specified height `h`. `h` must be under the maximum height. If the method is 'chebyshev', and the coefficients have not yet been calculated, they are created by calling `set_chebyshev_approximators`. Parameters ---------- h : float Height specified, [m] method : str One of 'full' (calculated rigorously) or 'chebyshev' Returns ------- V : float Volume of liquid in the tank up to the specified height, [m^3] Notes ----- ''' if method == 'full': return V_from_h(h, self.D, self.L, self.horizontal, self.sideA, self.sideB, self.sideA_a, self.sideB_a, self.sideA_f, self.sideA_k, self.sideB_f, self.sideB_k) elif method == 'chebyshev': if not self.chebyshev: self.set_chebyshev_approximators() return self.V_from_h_cheb(h) else: raise Exception("Allowable methods are 'full' or 'chebyshev'.")
[ "def", "V_from_h", "(", "self", ",", "h", ",", "method", "=", "'full'", ")", ":", "if", "method", "==", "'full'", ":", "return", "V_from_h", "(", "h", ",", "self", ".", "D", ",", "self", ".", "L", ",", "self", ".", "horizontal", ",", "self", ".", "sideA", ",", "self", ".", "sideB", ",", "self", ".", "sideA_a", ",", "self", ".", "sideB_a", ",", "self", ".", "sideA_f", ",", "self", ".", "sideA_k", ",", "self", ".", "sideB_f", ",", "self", ".", "sideB_k", ")", "elif", "method", "==", "'chebyshev'", ":", "if", "not", "self", ".", "chebyshev", ":", "self", ".", "set_chebyshev_approximators", "(", ")", "return", "self", ".", "V_from_h_cheb", "(", "h", ")", "else", ":", "raise", "Exception", "(", "\"Allowable methods are 'full' or 'chebyshev'.\"", ")" ]
r'''Method to calculate the volume of liquid in a fully defined tank given a specified height `h`. `h` must be under the maximum height. If the method is 'chebyshev', and the coefficients have not yet been calculated, they are created by calling `set_chebyshev_approximators`. Parameters ---------- h : float Height specified, [m] method : str One of 'full' (calculated rigorously) or 'chebyshev' Returns ------- V : float Volume of liquid in the tank up to the specified height, [m^3] Notes -----
[ "r", "Method", "to", "calculate", "the", "volume", "of", "liquid", "in", "a", "fully", "defined", "tank", "given", "a", "specified", "height", "h", ".", "h", "must", "be", "under", "the", "maximum", "height", ".", "If", "the", "method", "is", "chebyshev", "and", "the", "coefficients", "have", "not", "yet", "been", "calculated", "they", "are", "created", "by", "calling", "set_chebyshev_approximators", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1713-L1744
8,272
CalebBell/fluids
fluids/geometry.py
TANK.h_from_V
def h_from_V(self, V, method='spline'): r'''Method to calculate the height of liquid in a fully defined tank given a specified volume of liquid in it `V`. `V` must be under the maximum volume. If the method is 'spline', and the interpolation table is not yet defined, creates it by calling the method set_table. If the method is 'chebyshev', and the coefficients have not yet been calculated, they are created by calling `set_chebyshev_approximators`. Parameters ---------- V : float Volume of liquid in the tank up to the desired height, [m^3] method : str One of 'spline', 'chebyshev', or 'brenth' Returns ------- h : float Height of liquid at which the volume is as desired, [m] ''' if method == 'spline': if not self.table: self.set_table() return float(self.interp_h_from_V(V)) elif method == 'chebyshev': if not self.chebyshev: self.set_chebyshev_approximators() return self.h_from_V_cheb(V) elif method == 'brenth': to_solve = lambda h : self.V_from_h(h, method='full') - V return brenth(to_solve, self.h_max, 0) else: raise Exception("Allowable methods are 'full' or 'chebyshev', " "or 'brenth'.")
python
def h_from_V(self, V, method='spline'): r'''Method to calculate the height of liquid in a fully defined tank given a specified volume of liquid in it `V`. `V` must be under the maximum volume. If the method is 'spline', and the interpolation table is not yet defined, creates it by calling the method set_table. If the method is 'chebyshev', and the coefficients have not yet been calculated, they are created by calling `set_chebyshev_approximators`. Parameters ---------- V : float Volume of liquid in the tank up to the desired height, [m^3] method : str One of 'spline', 'chebyshev', or 'brenth' Returns ------- h : float Height of liquid at which the volume is as desired, [m] ''' if method == 'spline': if not self.table: self.set_table() return float(self.interp_h_from_V(V)) elif method == 'chebyshev': if not self.chebyshev: self.set_chebyshev_approximators() return self.h_from_V_cheb(V) elif method == 'brenth': to_solve = lambda h : self.V_from_h(h, method='full') - V return brenth(to_solve, self.h_max, 0) else: raise Exception("Allowable methods are 'full' or 'chebyshev', " "or 'brenth'.")
[ "def", "h_from_V", "(", "self", ",", "V", ",", "method", "=", "'spline'", ")", ":", "if", "method", "==", "'spline'", ":", "if", "not", "self", ".", "table", ":", "self", ".", "set_table", "(", ")", "return", "float", "(", "self", ".", "interp_h_from_V", "(", "V", ")", ")", "elif", "method", "==", "'chebyshev'", ":", "if", "not", "self", ".", "chebyshev", ":", "self", ".", "set_chebyshev_approximators", "(", ")", "return", "self", ".", "h_from_V_cheb", "(", "V", ")", "elif", "method", "==", "'brenth'", ":", "to_solve", "=", "lambda", "h", ":", "self", ".", "V_from_h", "(", "h", ",", "method", "=", "'full'", ")", "-", "V", "return", "brenth", "(", "to_solve", ",", "self", ".", "h_max", ",", "0", ")", "else", ":", "raise", "Exception", "(", "\"Allowable methods are 'full' or 'chebyshev', \"", "\"or 'brenth'.\"", ")" ]
r'''Method to calculate the height of liquid in a fully defined tank given a specified volume of liquid in it `V`. `V` must be under the maximum volume. If the method is 'spline', and the interpolation table is not yet defined, creates it by calling the method set_table. If the method is 'chebyshev', and the coefficients have not yet been calculated, they are created by calling `set_chebyshev_approximators`. Parameters ---------- V : float Volume of liquid in the tank up to the desired height, [m^3] method : str One of 'spline', 'chebyshev', or 'brenth' Returns ------- h : float Height of liquid at which the volume is as desired, [m]
[ "r", "Method", "to", "calculate", "the", "height", "of", "liquid", "in", "a", "fully", "defined", "tank", "given", "a", "specified", "volume", "of", "liquid", "in", "it", "V", ".", "V", "must", "be", "under", "the", "maximum", "volume", ".", "If", "the", "method", "is", "spline", "and", "the", "interpolation", "table", "is", "not", "yet", "defined", "creates", "it", "by", "calling", "the", "method", "set_table", ".", "If", "the", "method", "is", "chebyshev", "and", "the", "coefficients", "have", "not", "yet", "been", "calculated", "they", "are", "created", "by", "calling", "set_chebyshev_approximators", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1746-L1779
8,273
CalebBell/fluids
fluids/geometry.py
TANK.set_table
def set_table(self, n=100, dx=None): r'''Method to set an interpolation table of liquids levels versus volumes in the tank, for a fully defined tank. Normally run by the h_from_V method, this may be run prior to its use with a custom specification. Either the number of points on the table, or the vertical distance between steps may be specified. Parameters ---------- n : float, optional Number of points in the interpolation table, [-] dx : float, optional Vertical distance between steps in the interpolation table, [m] ''' if dx: self.heights = np.linspace(0, self.h_max, int(self.h_max/dx)+1) else: self.heights = np.linspace(0, self.h_max, n) self.volumes = [self.V_from_h(h) for h in self.heights] from scipy.interpolate import UnivariateSpline self.interp_h_from_V = UnivariateSpline(self.volumes, self.heights, ext=3, s=0.0) self.table = True
python
def set_table(self, n=100, dx=None): r'''Method to set an interpolation table of liquids levels versus volumes in the tank, for a fully defined tank. Normally run by the h_from_V method, this may be run prior to its use with a custom specification. Either the number of points on the table, or the vertical distance between steps may be specified. Parameters ---------- n : float, optional Number of points in the interpolation table, [-] dx : float, optional Vertical distance between steps in the interpolation table, [m] ''' if dx: self.heights = np.linspace(0, self.h_max, int(self.h_max/dx)+1) else: self.heights = np.linspace(0, self.h_max, n) self.volumes = [self.V_from_h(h) for h in self.heights] from scipy.interpolate import UnivariateSpline self.interp_h_from_V = UnivariateSpline(self.volumes, self.heights, ext=3, s=0.0) self.table = True
[ "def", "set_table", "(", "self", ",", "n", "=", "100", ",", "dx", "=", "None", ")", ":", "if", "dx", ":", "self", ".", "heights", "=", "np", ".", "linspace", "(", "0", ",", "self", ".", "h_max", ",", "int", "(", "self", ".", "h_max", "/", "dx", ")", "+", "1", ")", "else", ":", "self", ".", "heights", "=", "np", ".", "linspace", "(", "0", ",", "self", ".", "h_max", ",", "n", ")", "self", ".", "volumes", "=", "[", "self", ".", "V_from_h", "(", "h", ")", "for", "h", "in", "self", ".", "heights", "]", "from", "scipy", ".", "interpolate", "import", "UnivariateSpline", "self", ".", "interp_h_from_V", "=", "UnivariateSpline", "(", "self", ".", "volumes", ",", "self", ".", "heights", ",", "ext", "=", "3", ",", "s", "=", "0.0", ")", "self", ".", "table", "=", "True" ]
r'''Method to set an interpolation table of liquids levels versus volumes in the tank, for a fully defined tank. Normally run by the h_from_V method, this may be run prior to its use with a custom specification. Either the number of points on the table, or the vertical distance between steps may be specified. Parameters ---------- n : float, optional Number of points in the interpolation table, [-] dx : float, optional Vertical distance between steps in the interpolation table, [m]
[ "r", "Method", "to", "set", "an", "interpolation", "table", "of", "liquids", "levels", "versus", "volumes", "in", "the", "tank", "for", "a", "fully", "defined", "tank", ".", "Normally", "run", "by", "the", "h_from_V", "method", "this", "may", "be", "run", "prior", "to", "its", "use", "with", "a", "custom", "specification", ".", "Either", "the", "number", "of", "points", "on", "the", "table", "or", "the", "vertical", "distance", "between", "steps", "may", "be", "specified", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1781-L1802
8,274
CalebBell/fluids
fluids/geometry.py
TANK._V_solver_error
def _V_solver_error(self, Vtarget, D, L, horizontal, sideA, sideB, sideA_a, sideB_a, sideA_f, sideA_k, sideB_f, sideB_k, sideA_a_ratio, sideB_a_ratio): '''Function which uses only the variables given, and the TANK class itself, to determine how far from the desired volume, Vtarget, the volume produced by the specified parameters in a new TANK instance is. Should only be used by solve_tank_for_V method. ''' a = TANK(D=float(D), L=float(L), horizontal=horizontal, sideA=sideA, sideB=sideB, sideA_a=sideA_a, sideB_a=sideB_a, sideA_f=sideA_f, sideA_k=sideA_k, sideB_f=sideB_f, sideB_k=sideB_k, sideA_a_ratio=sideA_a_ratio, sideB_a_ratio=sideB_a_ratio) error = abs(Vtarget - a.V_total) return error
python
def _V_solver_error(self, Vtarget, D, L, horizontal, sideA, sideB, sideA_a, sideB_a, sideA_f, sideA_k, sideB_f, sideB_k, sideA_a_ratio, sideB_a_ratio): '''Function which uses only the variables given, and the TANK class itself, to determine how far from the desired volume, Vtarget, the volume produced by the specified parameters in a new TANK instance is. Should only be used by solve_tank_for_V method. ''' a = TANK(D=float(D), L=float(L), horizontal=horizontal, sideA=sideA, sideB=sideB, sideA_a=sideA_a, sideB_a=sideB_a, sideA_f=sideA_f, sideA_k=sideA_k, sideB_f=sideB_f, sideB_k=sideB_k, sideA_a_ratio=sideA_a_ratio, sideB_a_ratio=sideB_a_ratio) error = abs(Vtarget - a.V_total) return error
[ "def", "_V_solver_error", "(", "self", ",", "Vtarget", ",", "D", ",", "L", ",", "horizontal", ",", "sideA", ",", "sideB", ",", "sideA_a", ",", "sideB_a", ",", "sideA_f", ",", "sideA_k", ",", "sideB_f", ",", "sideB_k", ",", "sideA_a_ratio", ",", "sideB_a_ratio", ")", ":", "a", "=", "TANK", "(", "D", "=", "float", "(", "D", ")", ",", "L", "=", "float", "(", "L", ")", ",", "horizontal", "=", "horizontal", ",", "sideA", "=", "sideA", ",", "sideB", "=", "sideB", ",", "sideA_a", "=", "sideA_a", ",", "sideB_a", "=", "sideB_a", ",", "sideA_f", "=", "sideA_f", ",", "sideA_k", "=", "sideA_k", ",", "sideB_f", "=", "sideB_f", ",", "sideB_k", "=", "sideB_k", ",", "sideA_a_ratio", "=", "sideA_a_ratio", ",", "sideB_a_ratio", "=", "sideB_a_ratio", ")", "error", "=", "abs", "(", "Vtarget", "-", "a", ".", "V_total", ")", "return", "error" ]
Function which uses only the variables given, and the TANK class itself, to determine how far from the desired volume, Vtarget, the volume produced by the specified parameters in a new TANK instance is. Should only be used by solve_tank_for_V method.
[ "Function", "which", "uses", "only", "the", "variables", "given", "and", "the", "TANK", "class", "itself", "to", "determine", "how", "far", "from", "the", "desired", "volume", "Vtarget", "the", "volume", "produced", "by", "the", "specified", "parameters", "in", "a", "new", "TANK", "instance", "is", ".", "Should", "only", "be", "used", "by", "solve_tank_for_V", "method", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1843-L1856
8,275
CalebBell/fluids
fluids/geometry.py
PlateExchanger.plate_exchanger_identifier
def plate_exchanger_identifier(self): '''Method to create an identifying string in format 'L' + wavelength + 'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and amplitude are specified in units of mm and rounded to two decimal places. ''' s = ('L' + str(round(self.wavelength*1000, 2)) + 'A' + str(round(self.amplitude*1000, 2)) + 'B' + '-'.join([str(i) for i in self.chevron_angles])) return s
python
def plate_exchanger_identifier(self): '''Method to create an identifying string in format 'L' + wavelength + 'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and amplitude are specified in units of mm and rounded to two decimal places. ''' s = ('L' + str(round(self.wavelength*1000, 2)) + 'A' + str(round(self.amplitude*1000, 2)) + 'B' + '-'.join([str(i) for i in self.chevron_angles])) return s
[ "def", "plate_exchanger_identifier", "(", "self", ")", ":", "s", "=", "(", "'L'", "+", "str", "(", "round", "(", "self", ".", "wavelength", "*", "1000", ",", "2", ")", ")", "+", "'A'", "+", "str", "(", "round", "(", "self", ".", "amplitude", "*", "1000", ",", "2", ")", ")", "+", "'B'", "+", "'-'", ".", "join", "(", "[", "str", "(", "i", ")", "for", "i", "in", "self", ".", "chevron_angles", "]", ")", ")", "return", "s" ]
Method to create an identifying string in format 'L' + wavelength + 'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and amplitude are specified in units of mm and rounded to two decimal places.
[ "Method", "to", "create", "an", "identifying", "string", "in", "format", "L", "+", "wavelength", "+", "A", "+", "amplitude", "+", "B", "+", "chevron", "angle", "-", "chevron", "angle", ".", "Wavelength", "and", "amplitude", "are", "specified", "in", "units", "of", "mm", "and", "rounded", "to", "two", "decimal", "places", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L2163-L2171
8,276
CalebBell/fluids
fluids/numerics/__init__.py
linspace
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None): '''Port of numpy's linspace to pure python. Does not support dtype, and returns lists of floats. ''' num = int(num) start = start * 1. stop = stop * 1. if num <= 0: return [] if endpoint: if num == 1: return [start] step = (stop-start)/float((num-1)) if num == 1: step = nan y = [start] for _ in range(num-2): y.append(y[-1] + step) y.append(stop) else: step = (stop-start)/float(num) if num == 1: step = nan y = [start] for _ in range(num-1): y.append(y[-1] + step) if retstep: return y, step else: return y
python
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None): '''Port of numpy's linspace to pure python. Does not support dtype, and returns lists of floats. ''' num = int(num) start = start * 1. stop = stop * 1. if num <= 0: return [] if endpoint: if num == 1: return [start] step = (stop-start)/float((num-1)) if num == 1: step = nan y = [start] for _ in range(num-2): y.append(y[-1] + step) y.append(stop) else: step = (stop-start)/float(num) if num == 1: step = nan y = [start] for _ in range(num-1): y.append(y[-1] + step) if retstep: return y, step else: return y
[ "def", "linspace", "(", "start", ",", "stop", ",", "num", "=", "50", ",", "endpoint", "=", "True", ",", "retstep", "=", "False", ",", "dtype", "=", "None", ")", ":", "num", "=", "int", "(", "num", ")", "start", "=", "start", "*", "1.", "stop", "=", "stop", "*", "1.", "if", "num", "<=", "0", ":", "return", "[", "]", "if", "endpoint", ":", "if", "num", "==", "1", ":", "return", "[", "start", "]", "step", "=", "(", "stop", "-", "start", ")", "/", "float", "(", "(", "num", "-", "1", ")", ")", "if", "num", "==", "1", ":", "step", "=", "nan", "y", "=", "[", "start", "]", "for", "_", "in", "range", "(", "num", "-", "2", ")", ":", "y", ".", "append", "(", "y", "[", "-", "1", "]", "+", "step", ")", "y", ".", "append", "(", "stop", ")", "else", ":", "step", "=", "(", "stop", "-", "start", ")", "/", "float", "(", "num", ")", "if", "num", "==", "1", ":", "step", "=", "nan", "y", "=", "[", "start", "]", "for", "_", "in", "range", "(", "num", "-", "1", ")", ":", "y", ".", "append", "(", "y", "[", "-", "1", "]", "+", "step", ")", "if", "retstep", ":", "return", "y", ",", "step", "else", ":", "return", "y" ]
Port of numpy's linspace to pure python. Does not support dtype, and returns lists of floats.
[ "Port", "of", "numpy", "s", "linspace", "to", "pure", "python", ".", "Does", "not", "support", "dtype", "and", "returns", "lists", "of", "floats", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L361-L392
8,277
CalebBell/fluids
fluids/numerics/__init__.py
derivative
def derivative(func, x0, dx=1.0, n=1, args=(), order=3): '''Reimplementation of SciPy's derivative function, with more cached coefficients and without using numpy. If new coefficients not cached are needed, they are only calculated once and are remembered. ''' if order < n + 1: raise ValueError if order % 2 == 0: raise ValueError weights = central_diff_weights(order, n) tot = 0.0 ho = order >> 1 for k in range(order): tot += weights[k]*func(x0 + (k - ho)*dx, *args) return tot/product([dx]*n)
python
def derivative(func, x0, dx=1.0, n=1, args=(), order=3): '''Reimplementation of SciPy's derivative function, with more cached coefficients and without using numpy. If new coefficients not cached are needed, they are only calculated once and are remembered. ''' if order < n + 1: raise ValueError if order % 2 == 0: raise ValueError weights = central_diff_weights(order, n) tot = 0.0 ho = order >> 1 for k in range(order): tot += weights[k]*func(x0 + (k - ho)*dx, *args) return tot/product([dx]*n)
[ "def", "derivative", "(", "func", ",", "x0", ",", "dx", "=", "1.0", ",", "n", "=", "1", ",", "args", "=", "(", ")", ",", "order", "=", "3", ")", ":", "if", "order", "<", "n", "+", "1", ":", "raise", "ValueError", "if", "order", "%", "2", "==", "0", ":", "raise", "ValueError", "weights", "=", "central_diff_weights", "(", "order", ",", "n", ")", "tot", "=", "0.0", "ho", "=", "order", ">>", "1", "for", "k", "in", "range", "(", "order", ")", ":", "tot", "+=", "weights", "[", "k", "]", "*", "func", "(", "x0", "+", "(", "k", "-", "ho", ")", "*", "dx", ",", "*", "args", ")", "return", "tot", "/", "product", "(", "[", "dx", "]", "*", "n", ")" ]
Reimplementation of SciPy's derivative function, with more cached coefficients and without using numpy. If new coefficients not cached are needed, they are only calculated once and are remembered.
[ "Reimplementation", "of", "SciPy", "s", "derivative", "function", "with", "more", "cached", "coefficients", "and", "without", "using", "numpy", ".", "If", "new", "coefficients", "not", "cached", "are", "needed", "they", "are", "only", "calculated", "once", "and", "are", "remembered", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L547-L561
8,278
CalebBell/fluids
fluids/numerics/__init__.py
polyder
def polyder(c, m=1, scl=1, axis=0): '''not quite a copy of numpy's version because this was faster to implement. ''' c = list(c) cnt = int(m) if cnt == 0: return c n = len(c) if cnt >= n: c = c[:1]*0 else: for i in range(cnt): n = n - 1 c *= scl der = [0.0 for _ in range(n)] for j in range(n, 0, -1): der[j - 1] = j*c[j] c = der return c
python
def polyder(c, m=1, scl=1, axis=0): '''not quite a copy of numpy's version because this was faster to implement. ''' c = list(c) cnt = int(m) if cnt == 0: return c n = len(c) if cnt >= n: c = c[:1]*0 else: for i in range(cnt): n = n - 1 c *= scl der = [0.0 for _ in range(n)] for j in range(n, 0, -1): der[j - 1] = j*c[j] c = der return c
[ "def", "polyder", "(", "c", ",", "m", "=", "1", ",", "scl", "=", "1", ",", "axis", "=", "0", ")", ":", "c", "=", "list", "(", "c", ")", "cnt", "=", "int", "(", "m", ")", "if", "cnt", "==", "0", ":", "return", "c", "n", "=", "len", "(", "c", ")", "if", "cnt", ">=", "n", ":", "c", "=", "c", "[", ":", "1", "]", "*", "0", "else", ":", "for", "i", "in", "range", "(", "cnt", ")", ":", "n", "=", "n", "-", "1", "c", "*=", "scl", "der", "=", "[", "0.0", "for", "_", "in", "range", "(", "n", ")", "]", "for", "j", "in", "range", "(", "n", ",", "0", ",", "-", "1", ")", ":", "der", "[", "j", "-", "1", "]", "=", "j", "*", "c", "[", "j", "]", "c", "=", "der", "return", "c" ]
not quite a copy of numpy's version because this was faster to implement.
[ "not", "quite", "a", "copy", "of", "numpy", "s", "version", "because", "this", "was", "faster", "to", "implement", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L620-L640
8,279
CalebBell/fluids
fluids/numerics/__init__.py
horner_log
def horner_log(coeffs, log_coeff, x): '''Technically possible to save one addition of the last term of coeffs is removed but benchmarks said nothing was saved''' tot = 0.0 for c in coeffs: tot = tot*x + c return tot + log_coeff*log(x)
python
def horner_log(coeffs, log_coeff, x): '''Technically possible to save one addition of the last term of coeffs is removed but benchmarks said nothing was saved''' tot = 0.0 for c in coeffs: tot = tot*x + c return tot + log_coeff*log(x)
[ "def", "horner_log", "(", "coeffs", ",", "log_coeff", ",", "x", ")", ":", "tot", "=", "0.0", "for", "c", "in", "coeffs", ":", "tot", "=", "tot", "*", "x", "+", "c", "return", "tot", "+", "log_coeff", "*", "log", "(", "x", ")" ]
Technically possible to save one addition of the last term of coeffs is removed but benchmarks said nothing was saved
[ "Technically", "possible", "to", "save", "one", "addition", "of", "the", "last", "term", "of", "coeffs", "is", "removed", "but", "benchmarks", "said", "nothing", "was", "saved" ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L679-L685
8,280
CalebBell/fluids
fluids/numerics/__init__.py
implementation_optimize_tck
def implementation_optimize_tck(tck): '''Converts 1-d or 2-d splines calculated with SciPy's `splrep` or `bisplrep` to a format for fastest computation - lists in PyPy, and numpy arrays otherwise. Only implemented for 3 and 5 length `tck`s. ''' if IS_PYPY: return tck else: if len(tck) == 3: tck[0] = np.array(tck[0]) tck[1] = np.array(tck[1]) elif len(tck) == 5: tck[0] = np.array(tck[0]) tck[1] = np.array(tck[1]) tck[2] = np.array(tck[2]) else: raise NotImplementedError return tck
python
def implementation_optimize_tck(tck): '''Converts 1-d or 2-d splines calculated with SciPy's `splrep` or `bisplrep` to a format for fastest computation - lists in PyPy, and numpy arrays otherwise. Only implemented for 3 and 5 length `tck`s. ''' if IS_PYPY: return tck else: if len(tck) == 3: tck[0] = np.array(tck[0]) tck[1] = np.array(tck[1]) elif len(tck) == 5: tck[0] = np.array(tck[0]) tck[1] = np.array(tck[1]) tck[2] = np.array(tck[2]) else: raise NotImplementedError return tck
[ "def", "implementation_optimize_tck", "(", "tck", ")", ":", "if", "IS_PYPY", ":", "return", "tck", "else", ":", "if", "len", "(", "tck", ")", "==", "3", ":", "tck", "[", "0", "]", "=", "np", ".", "array", "(", "tck", "[", "0", "]", ")", "tck", "[", "1", "]", "=", "np", ".", "array", "(", "tck", "[", "1", "]", ")", "elif", "len", "(", "tck", ")", "==", "5", ":", "tck", "[", "0", "]", "=", "np", ".", "array", "(", "tck", "[", "0", "]", ")", "tck", "[", "1", "]", "=", "np", ".", "array", "(", "tck", "[", "1", "]", ")", "tck", "[", "2", "]", "=", "np", ".", "array", "(", "tck", "[", "2", "]", ")", "else", ":", "raise", "NotImplementedError", "return", "tck" ]
Converts 1-d or 2-d splines calculated with SciPy's `splrep` or `bisplrep` to a format for fastest computation - lists in PyPy, and numpy arrays otherwise. Only implemented for 3 and 5 length `tck`s.
[ "Converts", "1", "-", "d", "or", "2", "-", "d", "splines", "calculated", "with", "SciPy", "s", "splrep", "or", "bisplrep", "to", "a", "format", "for", "fastest", "computation", "-", "lists", "in", "PyPy", "and", "numpy", "arrays", "otherwise", ".", "Only", "implemented", "for", "3", "and", "5", "length", "tck", "s", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L870-L889
8,281
CalebBell/fluids
fluids/numerics/__init__.py
py_bisect
def py_bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter, ytol=None, full_output=False, disp=True): '''Port of SciPy's C bisect routine. ''' fa = f(a, *args) fb = f(b, *args) if fa*fb > 0.0: raise ValueError("f(a) and f(b) must have different signs") elif fa == 0.0: return a elif fb == 0.0: return b dm = b - a iterations = 0.0 for i in range(maxiter): dm *= 0.5 xm = a + dm fm = f(xm, *args) if fm*fa >= 0.0: a = xm abs_dm = fabs(dm) if fm == 0.0: return xm elif ytol is not None: if (abs_dm < xtol + rtol*abs_dm) and abs(fm) < ytol: return xm elif (abs_dm < xtol + rtol*abs_dm): return xm raise UnconvergedError("Failed to converge after %d iterations" %maxiter)
python
def py_bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter, ytol=None, full_output=False, disp=True): '''Port of SciPy's C bisect routine. ''' fa = f(a, *args) fb = f(b, *args) if fa*fb > 0.0: raise ValueError("f(a) and f(b) must have different signs") elif fa == 0.0: return a elif fb == 0.0: return b dm = b - a iterations = 0.0 for i in range(maxiter): dm *= 0.5 xm = a + dm fm = f(xm, *args) if fm*fa >= 0.0: a = xm abs_dm = fabs(dm) if fm == 0.0: return xm elif ytol is not None: if (abs_dm < xtol + rtol*abs_dm) and abs(fm) < ytol: return xm elif (abs_dm < xtol + rtol*abs_dm): return xm raise UnconvergedError("Failed to converge after %d iterations" %maxiter)
[ "def", "py_bisect", "(", "f", ",", "a", ",", "b", ",", "args", "=", "(", ")", ",", "xtol", "=", "_xtol", ",", "rtol", "=", "_rtol", ",", "maxiter", "=", "_iter", ",", "ytol", "=", "None", ",", "full_output", "=", "False", ",", "disp", "=", "True", ")", ":", "fa", "=", "f", "(", "a", ",", "*", "args", ")", "fb", "=", "f", "(", "b", ",", "*", "args", ")", "if", "fa", "*", "fb", ">", "0.0", ":", "raise", "ValueError", "(", "\"f(a) and f(b) must have different signs\"", ")", "elif", "fa", "==", "0.0", ":", "return", "a", "elif", "fb", "==", "0.0", ":", "return", "b", "dm", "=", "b", "-", "a", "iterations", "=", "0.0", "for", "i", "in", "range", "(", "maxiter", ")", ":", "dm", "*=", "0.5", "xm", "=", "a", "+", "dm", "fm", "=", "f", "(", "xm", ",", "*", "args", ")", "if", "fm", "*", "fa", ">=", "0.0", ":", "a", "=", "xm", "abs_dm", "=", "fabs", "(", "dm", ")", "if", "fm", "==", "0.0", ":", "return", "xm", "elif", "ytol", "is", "not", "None", ":", "if", "(", "abs_dm", "<", "xtol", "+", "rtol", "*", "abs_dm", ")", "and", "abs", "(", "fm", ")", "<", "ytol", ":", "return", "xm", "elif", "(", "abs_dm", "<", "xtol", "+", "rtol", "*", "abs_dm", ")", ":", "return", "xm", "raise", "UnconvergedError", "(", "\"Failed to converge after %d iterations\"", "%", "maxiter", ")" ]
Port of SciPy's C bisect routine.
[ "Port", "of", "SciPy", "s", "C", "bisect", "routine", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L1058-L1089
8,282
CalebBell/fluids
fluids/control_valve.py
is_choked_turbulent_l
def is_choked_turbulent_l(dP, P1, Psat, FF, FL=None, FLP=None, FP=None): r'''Calculates if a liquid flow in IEC 60534 calculations is critical or not, for use in IEC 60534 liquid valve sizing calculations. Either FL may be provided or FLP and FP, depending on the calculation process. .. math:: \Delta P > F_L^2(P_1 - F_F P_{sat}) .. math:: \Delta P >= \left(\frac{F_{LP}}{F_P}\right)^2(P_1 - F_F P_{sat}) Parameters ---------- dP : float Differential pressure across the valve, with reducer/expanders [Pa] P1 : float Pressure of the fluid before the valve and reducers/expanders [Pa] Psat : float Saturation pressure of the fluid at inlet temperature [Pa] FF : float Liquid critical pressure ratio factor [-] FL : float, optional Liquid pressure recovery factor of a control valve without attached fittings [-] FLP : float, optional Combined liquid pressure recovery factor with piping geometry factor, for a control valve with attached fittings [-] FP : float, optional Piping geometry factor [-] Returns ------- choked : bool Whether or not the flow is choked [-] Examples -------- >>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.9) False >>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.6) True References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 ''' if FLP and FP: return dP >= (FLP/FP)**2*(P1-FF*Psat) elif FL: return dP >= FL**2*(P1-FF*Psat) else: raise Exception('Either (FLP and FP) or FL is needed')
python
def is_choked_turbulent_l(dP, P1, Psat, FF, FL=None, FLP=None, FP=None): r'''Calculates if a liquid flow in IEC 60534 calculations is critical or not, for use in IEC 60534 liquid valve sizing calculations. Either FL may be provided or FLP and FP, depending on the calculation process. .. math:: \Delta P > F_L^2(P_1 - F_F P_{sat}) .. math:: \Delta P >= \left(\frac{F_{LP}}{F_P}\right)^2(P_1 - F_F P_{sat}) Parameters ---------- dP : float Differential pressure across the valve, with reducer/expanders [Pa] P1 : float Pressure of the fluid before the valve and reducers/expanders [Pa] Psat : float Saturation pressure of the fluid at inlet temperature [Pa] FF : float Liquid critical pressure ratio factor [-] FL : float, optional Liquid pressure recovery factor of a control valve without attached fittings [-] FLP : float, optional Combined liquid pressure recovery factor with piping geometry factor, for a control valve with attached fittings [-] FP : float, optional Piping geometry factor [-] Returns ------- choked : bool Whether or not the flow is choked [-] Examples -------- >>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.9) False >>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.6) True References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 ''' if FLP and FP: return dP >= (FLP/FP)**2*(P1-FF*Psat) elif FL: return dP >= FL**2*(P1-FF*Psat) else: raise Exception('Either (FLP and FP) or FL is needed')
[ "def", "is_choked_turbulent_l", "(", "dP", ",", "P1", ",", "Psat", ",", "FF", ",", "FL", "=", "None", ",", "FLP", "=", "None", ",", "FP", "=", "None", ")", ":", "if", "FLP", "and", "FP", ":", "return", "dP", ">=", "(", "FLP", "/", "FP", ")", "**", "2", "*", "(", "P1", "-", "FF", "*", "Psat", ")", "elif", "FL", ":", "return", "dP", ">=", "FL", "**", "2", "*", "(", "P1", "-", "FF", "*", "Psat", ")", "else", ":", "raise", "Exception", "(", "'Either (FLP and FP) or FL is needed'", ")" ]
r'''Calculates if a liquid flow in IEC 60534 calculations is critical or not, for use in IEC 60534 liquid valve sizing calculations. Either FL may be provided or FLP and FP, depending on the calculation process. .. math:: \Delta P > F_L^2(P_1 - F_F P_{sat}) .. math:: \Delta P >= \left(\frac{F_{LP}}{F_P}\right)^2(P_1 - F_F P_{sat}) Parameters ---------- dP : float Differential pressure across the valve, with reducer/expanders [Pa] P1 : float Pressure of the fluid before the valve and reducers/expanders [Pa] Psat : float Saturation pressure of the fluid at inlet temperature [Pa] FF : float Liquid critical pressure ratio factor [-] FL : float, optional Liquid pressure recovery factor of a control valve without attached fittings [-] FLP : float, optional Combined liquid pressure recovery factor with piping geometry factor, for a control valve with attached fittings [-] FP : float, optional Piping geometry factor [-] Returns ------- choked : bool Whether or not the flow is choked [-] Examples -------- >>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.9) False >>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.6) True References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007
[ "r", "Calculates", "if", "a", "liquid", "flow", "in", "IEC", "60534", "calculations", "is", "critical", "or", "not", "for", "use", "in", "IEC", "60534", "liquid", "valve", "sizing", "calculations", ".", "Either", "FL", "may", "be", "provided", "or", "FLP", "and", "FP", "depending", "on", "the", "calculation", "process", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/control_valve.py#L259-L310
8,283
CalebBell/fluids
fluids/control_valve.py
is_choked_turbulent_g
def is_choked_turbulent_g(x, Fgamma, xT=None, xTP=None): r'''Calculates if a gas flow in IEC 60534 calculations is critical or not, for use in IEC 60534 gas valve sizing calculations. Either xT or xTP must be provided, depending on the calculation process. .. math:: x \ge F_\gamma x_T .. math:: x \ge F_\gamma x_{TP} Parameters ---------- x : float Differential pressure over inlet pressure, [-] Fgamma : float Specific heat ratio factor [-] xT : float, optional Pressure difference ratio factor of a valve without fittings at choked flow [-] xTP : float Pressure difference ratio factor of a valve with fittings at choked flow [-] Returns ------- choked : bool Whether or not the flow is choked [-] Examples -------- Example 3, compressible flow, non-choked with attached fittings: >>> is_choked_turbulent_g(0.544, 0.929, 0.6) False >>> is_choked_turbulent_g(0.544, 0.929, xTP=0.625) False References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 ''' if xT: return x >= Fgamma*xT elif xTP: return x >= Fgamma*xTP else: raise Exception('Either xT or xTP is needed')
python
def is_choked_turbulent_g(x, Fgamma, xT=None, xTP=None): r'''Calculates if a gas flow in IEC 60534 calculations is critical or not, for use in IEC 60534 gas valve sizing calculations. Either xT or xTP must be provided, depending on the calculation process. .. math:: x \ge F_\gamma x_T .. math:: x \ge F_\gamma x_{TP} Parameters ---------- x : float Differential pressure over inlet pressure, [-] Fgamma : float Specific heat ratio factor [-] xT : float, optional Pressure difference ratio factor of a valve without fittings at choked flow [-] xTP : float Pressure difference ratio factor of a valve with fittings at choked flow [-] Returns ------- choked : bool Whether or not the flow is choked [-] Examples -------- Example 3, compressible flow, non-choked with attached fittings: >>> is_choked_turbulent_g(0.544, 0.929, 0.6) False >>> is_choked_turbulent_g(0.544, 0.929, xTP=0.625) False References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 ''' if xT: return x >= Fgamma*xT elif xTP: return x >= Fgamma*xTP else: raise Exception('Either xT or xTP is needed')
[ "def", "is_choked_turbulent_g", "(", "x", ",", "Fgamma", ",", "xT", "=", "None", ",", "xTP", "=", "None", ")", ":", "if", "xT", ":", "return", "x", ">=", "Fgamma", "*", "xT", "elif", "xTP", ":", "return", "x", ">=", "Fgamma", "*", "xTP", "else", ":", "raise", "Exception", "(", "'Either xT or xTP is needed'", ")" ]
r'''Calculates if a gas flow in IEC 60534 calculations is critical or not, for use in IEC 60534 gas valve sizing calculations. Either xT or xTP must be provided, depending on the calculation process. .. math:: x \ge F_\gamma x_T .. math:: x \ge F_\gamma x_{TP} Parameters ---------- x : float Differential pressure over inlet pressure, [-] Fgamma : float Specific heat ratio factor [-] xT : float, optional Pressure difference ratio factor of a valve without fittings at choked flow [-] xTP : float Pressure difference ratio factor of a valve with fittings at choked flow [-] Returns ------- choked : bool Whether or not the flow is choked [-] Examples -------- Example 3, compressible flow, non-choked with attached fittings: >>> is_choked_turbulent_g(0.544, 0.929, 0.6) False >>> is_choked_turbulent_g(0.544, 0.929, xTP=0.625) False References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007
[ "r", "Calculates", "if", "a", "gas", "flow", "in", "IEC", "60534", "calculations", "is", "critical", "or", "not", "for", "use", "in", "IEC", "60534", "gas", "valve", "sizing", "calculations", ".", "Either", "xT", "or", "xTP", "must", "be", "provided", "depending", "on", "the", "calculation", "process", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/control_valve.py#L313-L360
8,284
CalebBell/fluids
fluids/control_valve.py
Reynolds_valve
def Reynolds_valve(nu, Q, D1, FL, Fd, C): r'''Calculates Reynolds number of a control valve for a liquid or gas flowing through it at a specified Q, for a specified D1, FL, Fd, C, and with kinematic viscosity `nu` according to IEC 60534 calculations. .. math:: Re_v = \frac{N_4 F_d Q}{\nu \sqrt{C F_L}}\left(\frac{F_L^2 C^2} {N_2D^4} +1\right)^{1/4} Parameters ---------- nu : float Kinematic viscosity, [m^2/s] Q : float Volumetric flow rate of the fluid [m^3/s] D1 : float Diameter of the pipe before the valve [m] FL : float, optional Liquid pressure recovery factor of a control valve without attached fittings [] Fd : float Valve style modifier [-] C : float Metric Kv valve flow coefficient (flow rate of water at a pressure drop of 1 bar) [m^3/hr] Returns ------- Rev : float Valve reynolds number [-] Examples -------- >>> Reynolds_valve(3.26e-07, 360, 150.0, 0.9, 0.46, 165) 2966984.7525455453 References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 ''' return N4*Fd*Q/nu/(C*FL)**0.5*(FL**2*C**2/(N2*D1**4) + 1)**0.25
python
def Reynolds_valve(nu, Q, D1, FL, Fd, C): r'''Calculates Reynolds number of a control valve for a liquid or gas flowing through it at a specified Q, for a specified D1, FL, Fd, C, and with kinematic viscosity `nu` according to IEC 60534 calculations. .. math:: Re_v = \frac{N_4 F_d Q}{\nu \sqrt{C F_L}}\left(\frac{F_L^2 C^2} {N_2D^4} +1\right)^{1/4} Parameters ---------- nu : float Kinematic viscosity, [m^2/s] Q : float Volumetric flow rate of the fluid [m^3/s] D1 : float Diameter of the pipe before the valve [m] FL : float, optional Liquid pressure recovery factor of a control valve without attached fittings [] Fd : float Valve style modifier [-] C : float Metric Kv valve flow coefficient (flow rate of water at a pressure drop of 1 bar) [m^3/hr] Returns ------- Rev : float Valve reynolds number [-] Examples -------- >>> Reynolds_valve(3.26e-07, 360, 150.0, 0.9, 0.46, 165) 2966984.7525455453 References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 ''' return N4*Fd*Q/nu/(C*FL)**0.5*(FL**2*C**2/(N2*D1**4) + 1)**0.25
[ "def", "Reynolds_valve", "(", "nu", ",", "Q", ",", "D1", ",", "FL", ",", "Fd", ",", "C", ")", ":", "return", "N4", "*", "Fd", "*", "Q", "/", "nu", "/", "(", "C", "*", "FL", ")", "**", "0.5", "*", "(", "FL", "**", "2", "*", "C", "**", "2", "/", "(", "N2", "*", "D1", "**", "4", ")", "+", "1", ")", "**", "0.25" ]
r'''Calculates Reynolds number of a control valve for a liquid or gas flowing through it at a specified Q, for a specified D1, FL, Fd, C, and with kinematic viscosity `nu` according to IEC 60534 calculations. .. math:: Re_v = \frac{N_4 F_d Q}{\nu \sqrt{C F_L}}\left(\frac{F_L^2 C^2} {N_2D^4} +1\right)^{1/4} Parameters ---------- nu : float Kinematic viscosity, [m^2/s] Q : float Volumetric flow rate of the fluid [m^3/s] D1 : float Diameter of the pipe before the valve [m] FL : float, optional Liquid pressure recovery factor of a control valve without attached fittings [] Fd : float Valve style modifier [-] C : float Metric Kv valve flow coefficient (flow rate of water at a pressure drop of 1 bar) [m^3/hr] Returns ------- Rev : float Valve reynolds number [-] Examples -------- >>> Reynolds_valve(3.26e-07, 360, 150.0, 0.9, 0.46, 165) 2966984.7525455453 References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007
[ "r", "Calculates", "Reynolds", "number", "of", "a", "control", "valve", "for", "a", "liquid", "or", "gas", "flowing", "through", "it", "at", "a", "specified", "Q", "for", "a", "specified", "D1", "FL", "Fd", "C", "and", "with", "kinematic", "viscosity", "nu", "according", "to", "IEC", "60534", "calculations", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/control_valve.py#L363-L403
8,285
CalebBell/fluids
fluids/control_valve.py
Reynolds_factor
def Reynolds_factor(FL, C, d, Rev, full_trim=True): r'''Calculates the Reynolds number factor `FR` for a valve with a Reynolds number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery factor `FL`, and with either full or reduced trim, all according to IEC 60534 calculations. If full trim: .. math:: F_{R,1a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_1^{0.25}}\right)\log_{10} \left(\frac{Re_v}{10000}\right) .. math:: F_{R,2} = \min(\frac{0.026}{F_L}\sqrt{n_1 Re_v},\; 1) .. math:: n_1 = \frac{N_2}{\left(\frac{C}{d^2}\right)^2} .. math:: F_R = F_{R,2} \text{ if Rev < 10 else } \min(F_{R,1a}, F_{R,2}) Otherwise : .. math:: F_{R,3a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_2^{0.25}}\right)\log_{10} \left(\frac{Re_v}{10000}\right) .. math:: F_{R,4} = \frac{0.026}{F_L}\sqrt{n_2 Re_v} .. math:: n_2 = 1 + N_{32}\left(\frac{C}{d}\right)^{2/3} .. math:: F_R = F_{R,4} \text{ if Rev < 10 else } \min(F_{R,3a}, F_{R,4}) Parameters ---------- FL : float Liquid pressure recovery factor of a control valve without attached fittings [] C : float Metric Kv valve flow coefficient (flow rate of water at a pressure drop of 1 bar) [m^3/hr] d : float Diameter of the valve [m] Rev : float Valve reynolds number [-] full_trim : bool Whether or not the valve has full trim Returns ------- FR : float Reynolds number factor for laminar or transitional flow [] Examples -------- In Example 4, compressible flow with small flow trim sized for gas flow (Cv in the problem was converted to Kv here to make FR match with N32, N2): >>> Reynolds_factor(FL=0.98, C=0.015483, d=15., Rev=1202., full_trim=False) 0.7148753122302025 References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 ''' if full_trim: n1 = N2/(min(C/d**2, 0.04))**2 # C/d**2 must not exceed 0.04 FR_1a = 1 + (0.33*FL**0.5)/n1**0.25*log10(Rev/10000.) FR_2 = 0.026/FL*(n1*Rev)**0.5 if Rev < 10: FR = FR_2 else: FR = min(FR_2, FR_1a) else: n2 = 1 + N32*(C/d**2)**(2/3.) FR_3a = 1 + (0.33*FL**0.5)/n2**0.25*log10(Rev/10000.) FR_4 = min(0.026/FL*(n2*Rev)**0.5, 1) if Rev < 10: FR = FR_4 else: FR = min(FR_3a, FR_4) return FR
python
def Reynolds_factor(FL, C, d, Rev, full_trim=True): r'''Calculates the Reynolds number factor `FR` for a valve with a Reynolds number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery factor `FL`, and with either full or reduced trim, all according to IEC 60534 calculations. If full trim: .. math:: F_{R,1a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_1^{0.25}}\right)\log_{10} \left(\frac{Re_v}{10000}\right) .. math:: F_{R,2} = \min(\frac{0.026}{F_L}\sqrt{n_1 Re_v},\; 1) .. math:: n_1 = \frac{N_2}{\left(\frac{C}{d^2}\right)^2} .. math:: F_R = F_{R,2} \text{ if Rev < 10 else } \min(F_{R,1a}, F_{R,2}) Otherwise : .. math:: F_{R,3a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_2^{0.25}}\right)\log_{10} \left(\frac{Re_v}{10000}\right) .. math:: F_{R,4} = \frac{0.026}{F_L}\sqrt{n_2 Re_v} .. math:: n_2 = 1 + N_{32}\left(\frac{C}{d}\right)^{2/3} .. math:: F_R = F_{R,4} \text{ if Rev < 10 else } \min(F_{R,3a}, F_{R,4}) Parameters ---------- FL : float Liquid pressure recovery factor of a control valve without attached fittings [] C : float Metric Kv valve flow coefficient (flow rate of water at a pressure drop of 1 bar) [m^3/hr] d : float Diameter of the valve [m] Rev : float Valve reynolds number [-] full_trim : bool Whether or not the valve has full trim Returns ------- FR : float Reynolds number factor for laminar or transitional flow [] Examples -------- In Example 4, compressible flow with small flow trim sized for gas flow (Cv in the problem was converted to Kv here to make FR match with N32, N2): >>> Reynolds_factor(FL=0.98, C=0.015483, d=15., Rev=1202., full_trim=False) 0.7148753122302025 References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007 ''' if full_trim: n1 = N2/(min(C/d**2, 0.04))**2 # C/d**2 must not exceed 0.04 FR_1a = 1 + (0.33*FL**0.5)/n1**0.25*log10(Rev/10000.) FR_2 = 0.026/FL*(n1*Rev)**0.5 if Rev < 10: FR = FR_2 else: FR = min(FR_2, FR_1a) else: n2 = 1 + N32*(C/d**2)**(2/3.) FR_3a = 1 + (0.33*FL**0.5)/n2**0.25*log10(Rev/10000.) FR_4 = min(0.026/FL*(n2*Rev)**0.5, 1) if Rev < 10: FR = FR_4 else: FR = min(FR_3a, FR_4) return FR
[ "def", "Reynolds_factor", "(", "FL", ",", "C", ",", "d", ",", "Rev", ",", "full_trim", "=", "True", ")", ":", "if", "full_trim", ":", "n1", "=", "N2", "/", "(", "min", "(", "C", "/", "d", "**", "2", ",", "0.04", ")", ")", "**", "2", "# C/d**2 must not exceed 0.04", "FR_1a", "=", "1", "+", "(", "0.33", "*", "FL", "**", "0.5", ")", "/", "n1", "**", "0.25", "*", "log10", "(", "Rev", "/", "10000.", ")", "FR_2", "=", "0.026", "/", "FL", "*", "(", "n1", "*", "Rev", ")", "**", "0.5", "if", "Rev", "<", "10", ":", "FR", "=", "FR_2", "else", ":", "FR", "=", "min", "(", "FR_2", ",", "FR_1a", ")", "else", ":", "n2", "=", "1", "+", "N32", "*", "(", "C", "/", "d", "**", "2", ")", "**", "(", "2", "/", "3.", ")", "FR_3a", "=", "1", "+", "(", "0.33", "*", "FL", "**", "0.5", ")", "/", "n2", "**", "0.25", "*", "log10", "(", "Rev", "/", "10000.", ")", "FR_4", "=", "min", "(", "0.026", "/", "FL", "*", "(", "n2", "*", "Rev", ")", "**", "0.5", ",", "1", ")", "if", "Rev", "<", "10", ":", "FR", "=", "FR_4", "else", ":", "FR", "=", "min", "(", "FR_3a", ",", "FR_4", ")", "return", "FR" ]
r'''Calculates the Reynolds number factor `FR` for a valve with a Reynolds number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery factor `FL`, and with either full or reduced trim, all according to IEC 60534 calculations. If full trim: .. math:: F_{R,1a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_1^{0.25}}\right)\log_{10} \left(\frac{Re_v}{10000}\right) .. math:: F_{R,2} = \min(\frac{0.026}{F_L}\sqrt{n_1 Re_v},\; 1) .. math:: n_1 = \frac{N_2}{\left(\frac{C}{d^2}\right)^2} .. math:: F_R = F_{R,2} \text{ if Rev < 10 else } \min(F_{R,1a}, F_{R,2}) Otherwise : .. math:: F_{R,3a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_2^{0.25}}\right)\log_{10} \left(\frac{Re_v}{10000}\right) .. math:: F_{R,4} = \frac{0.026}{F_L}\sqrt{n_2 Re_v} .. math:: n_2 = 1 + N_{32}\left(\frac{C}{d}\right)^{2/3} .. math:: F_R = F_{R,4} \text{ if Rev < 10 else } \min(F_{R,3a}, F_{R,4}) Parameters ---------- FL : float Liquid pressure recovery factor of a control valve without attached fittings [] C : float Metric Kv valve flow coefficient (flow rate of water at a pressure drop of 1 bar) [m^3/hr] d : float Diameter of the valve [m] Rev : float Valve reynolds number [-] full_trim : bool Whether or not the valve has full trim Returns ------- FR : float Reynolds number factor for laminar or transitional flow [] Examples -------- In Example 4, compressible flow with small flow trim sized for gas flow (Cv in the problem was converted to Kv here to make FR match with N32, N2): >>> Reynolds_factor(FL=0.98, C=0.015483, d=15., Rev=1202., full_trim=False) 0.7148753122302025 References ---------- .. [1] IEC 60534-2-1 / ISA-75.01.01-2007
[ "r", "Calculates", "the", "Reynolds", "number", "factor", "FR", "for", "a", "valve", "with", "a", "Reynolds", "number", "Rev", "diameter", "d", "flow", "coefficient", "C", "liquid", "pressure", "recovery", "factor", "FL", "and", "with", "either", "full", "or", "reduced", "trim", "all", "according", "to", "IEC", "60534", "calculations", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/control_valve.py#L461-L547
8,286
CalebBell/fluids
fluids/units.py
func_args
def func_args(func): '''Basic function which returns a tuple of arguments of a function or method. ''' try: return tuple(inspect.signature(func).parameters) except: return tuple(inspect.getargspec(func).args)
python
def func_args(func): '''Basic function which returns a tuple of arguments of a function or method. ''' try: return tuple(inspect.signature(func).parameters) except: return tuple(inspect.getargspec(func).args)
[ "def", "func_args", "(", "func", ")", ":", "try", ":", "return", "tuple", "(", "inspect", ".", "signature", "(", "func", ")", ".", "parameters", ")", "except", ":", "return", "tuple", "(", "inspect", ".", "getargspec", "(", "func", ")", ".", "args", ")" ]
Basic function which returns a tuple of arguments of a function or method.
[ "Basic", "function", "which", "returns", "a", "tuple", "of", "arguments", "of", "a", "function", "or", "method", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/units.py#L51-L58
8,287
CalebBell/fluids
fluids/optional/pychebfun.py
cast_scalar
def cast_scalar(method): """ Cast scalars to constant interpolating objects """ @wraps(method) def new_method(self, other): if np.isscalar(other): other = type(self)([other],self.domain()) return method(self, other) return new_method
python
def cast_scalar(method): """ Cast scalars to constant interpolating objects """ @wraps(method) def new_method(self, other): if np.isscalar(other): other = type(self)([other],self.domain()) return method(self, other) return new_method
[ "def", "cast_scalar", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "new_method", "(", "self", ",", "other", ")", ":", "if", "np", ".", "isscalar", "(", "other", ")", ":", "other", "=", "type", "(", "self", ")", "(", "[", "other", "]", ",", "self", ".", "domain", "(", ")", ")", "return", "method", "(", "self", ",", "other", ")", "return", "new_method" ]
Cast scalars to constant interpolating objects
[ "Cast", "scalars", "to", "constant", "interpolating", "objects" ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L75-L84
8,288
CalebBell/fluids
fluids/optional/pychebfun.py
dct
def dct(data): """ Compute DCT using FFT """ N = len(data)//2 fftdata = fftpack.fft(data, axis=0)[:N+1] fftdata /= N fftdata[0] /= 2. fftdata[-1] /= 2. if np.isrealobj(data): data = np.real(fftdata) else: data = fftdata return data
python
def dct(data): """ Compute DCT using FFT """ N = len(data)//2 fftdata = fftpack.fft(data, axis=0)[:N+1] fftdata /= N fftdata[0] /= 2. fftdata[-1] /= 2. if np.isrealobj(data): data = np.real(fftdata) else: data = fftdata return data
[ "def", "dct", "(", "data", ")", ":", "N", "=", "len", "(", "data", ")", "//", "2", "fftdata", "=", "fftpack", ".", "fft", "(", "data", ",", "axis", "=", "0", ")", "[", ":", "N", "+", "1", "]", "fftdata", "/=", "N", "fftdata", "[", "0", "]", "/=", "2.", "fftdata", "[", "-", "1", "]", "/=", "2.", "if", "np", ".", "isrealobj", "(", "data", ")", ":", "data", "=", "np", ".", "real", "(", "fftdata", ")", "else", ":", "data", "=", "fftdata", "return", "data" ]
Compute DCT using FFT
[ "Compute", "DCT", "using", "FFT" ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L637-L650
8,289
CalebBell/fluids
fluids/optional/pychebfun.py
Polyfun._cutoff
def _cutoff(self, coeffs, vscale): """ Compute cutoff index after which the coefficients are deemed negligible. """ bnd = self._threshold(vscale) inds = np.nonzero(abs(coeffs) >= bnd) if len(inds[0]): N = inds[0][-1] else: N = 0 return N+1
python
def _cutoff(self, coeffs, vscale): """ Compute cutoff index after which the coefficients are deemed negligible. """ bnd = self._threshold(vscale) inds = np.nonzero(abs(coeffs) >= bnd) if len(inds[0]): N = inds[0][-1] else: N = 0 return N+1
[ "def", "_cutoff", "(", "self", ",", "coeffs", ",", "vscale", ")", ":", "bnd", "=", "self", ".", "_threshold", "(", "vscale", ")", "inds", "=", "np", ".", "nonzero", "(", "abs", "(", "coeffs", ")", ">=", "bnd", ")", "if", "len", "(", "inds", "[", "0", "]", ")", ":", "N", "=", "inds", "[", "0", "]", "[", "-", "1", "]", "else", ":", "N", "=", "0", "return", "N", "+", "1" ]
Compute cutoff index after which the coefficients are deemed negligible.
[ "Compute", "cutoff", "index", "after", "which", "the", "coefficients", "are", "deemed", "negligible", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L203-L213
8,290
CalebBell/fluids
fluids/optional/pychebfun.py
Polyfun.same_domain
def same_domain(self, fun2): """ Returns True if the domains of two objects are the same. """ return np.allclose(self.domain(), fun2.domain(), rtol=1e-14, atol=1e-14)
python
def same_domain(self, fun2): """ Returns True if the domains of two objects are the same. """ return np.allclose(self.domain(), fun2.domain(), rtol=1e-14, atol=1e-14)
[ "def", "same_domain", "(", "self", ",", "fun2", ")", ":", "return", "np", ".", "allclose", "(", "self", ".", "domain", "(", ")", ",", "fun2", ".", "domain", "(", ")", ",", "rtol", "=", "1e-14", ",", "atol", "=", "1e-14", ")" ]
Returns True if the domains of two objects are the same.
[ "Returns", "True", "if", "the", "domains", "of", "two", "objects", "are", "the", "same", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L241-L245
8,291
CalebBell/fluids
fluids/optional/pychebfun.py
Polyfun.restrict
def restrict(self,subinterval): """ Return a Polyfun that matches self on subinterval. """ if (subinterval[0] < self._domain[0]) or (subinterval[1] > self._domain[1]): raise ValueError("Can only restrict to subinterval") return self.from_function(self, subinterval)
python
def restrict(self,subinterval): """ Return a Polyfun that matches self on subinterval. """ if (subinterval[0] < self._domain[0]) or (subinterval[1] > self._domain[1]): raise ValueError("Can only restrict to subinterval") return self.from_function(self, subinterval)
[ "def", "restrict", "(", "self", ",", "subinterval", ")", ":", "if", "(", "subinterval", "[", "0", "]", "<", "self", ".", "_domain", "[", "0", "]", ")", "or", "(", "subinterval", "[", "1", "]", ">", "self", ".", "_domain", "[", "1", "]", ")", ":", "raise", "ValueError", "(", "\"Can only restrict to subinterval\"", ")", "return", "self", ".", "from_function", "(", "self", ",", "subinterval", ")" ]
Return a Polyfun that matches self on subinterval.
[ "Return", "a", "Polyfun", "that", "matches", "self", "on", "subinterval", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L395-L401
8,292
CalebBell/fluids
fluids/optional/pychebfun.py
Chebfun.basis
def basis(self, n): """ Chebyshev basis functions T_n. """ if n == 0: return self(np.array([1.])) vals = np.ones(n+1) vals[1::2] = -1 return self(vals)
python
def basis(self, n): """ Chebyshev basis functions T_n. """ if n == 0: return self(np.array([1.])) vals = np.ones(n+1) vals[1::2] = -1 return self(vals)
[ "def", "basis", "(", "self", ",", "n", ")", ":", "if", "n", "==", "0", ":", "return", "self", "(", "np", ".", "array", "(", "[", "1.", "]", ")", ")", "vals", "=", "np", ".", "ones", "(", "n", "+", "1", ")", "vals", "[", "1", ":", ":", "2", "]", "=", "-", "1", "return", "self", "(", "vals", ")" ]
Chebyshev basis functions T_n.
[ "Chebyshev", "basis", "functions", "T_n", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L435-L443
8,293
CalebBell/fluids
fluids/optional/pychebfun.py
Chebfun.sum
def sum(self): """ Evaluate the integral over the given interval using Clenshaw-Curtis quadrature. """ ak = self.coefficients() ak2 = ak[::2] n = len(ak2) Tints = 2/(1-(2*np.arange(n))**2) val = np.sum((Tints*ak2.T).T, axis=0) a_, b_ = self.domain() return 0.5*(b_-a_)*val
python
def sum(self): """ Evaluate the integral over the given interval using Clenshaw-Curtis quadrature. """ ak = self.coefficients() ak2 = ak[::2] n = len(ak2) Tints = 2/(1-(2*np.arange(n))**2) val = np.sum((Tints*ak2.T).T, axis=0) a_, b_ = self.domain() return 0.5*(b_-a_)*val
[ "def", "sum", "(", "self", ")", ":", "ak", "=", "self", ".", "coefficients", "(", ")", "ak2", "=", "ak", "[", ":", ":", "2", "]", "n", "=", "len", "(", "ak2", ")", "Tints", "=", "2", "/", "(", "1", "-", "(", "2", "*", "np", ".", "arange", "(", "n", ")", ")", "**", "2", ")", "val", "=", "np", ".", "sum", "(", "(", "Tints", "*", "ak2", ".", "T", ")", ".", "T", ",", "axis", "=", "0", ")", "a_", ",", "b_", "=", "self", ".", "domain", "(", ")", "return", "0.5", "*", "(", "b_", "-", "a_", ")", "*", "val" ]
Evaluate the integral over the given interval using Clenshaw-Curtis quadrature.
[ "Evaluate", "the", "integral", "over", "the", "given", "interval", "using", "Clenshaw", "-", "Curtis", "quadrature", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L449-L460
8,294
CalebBell/fluids
fluids/optional/pychebfun.py
Chebfun.integrate
def integrate(self): """ Return the object representing the primitive of self over the domain. The output starts at zero on the left-hand side of the domain. """ coeffs = self.coefficients() a,b = self.domain() int_coeffs = 0.5*(b-a)*poly.chebyshev.chebint(coeffs) antiderivative = self.from_coeff(int_coeffs, domain=self.domain()) return antiderivative - antiderivative(a)
python
def integrate(self): """ Return the object representing the primitive of self over the domain. The output starts at zero on the left-hand side of the domain. """ coeffs = self.coefficients() a,b = self.domain() int_coeffs = 0.5*(b-a)*poly.chebyshev.chebint(coeffs) antiderivative = self.from_coeff(int_coeffs, domain=self.domain()) return antiderivative - antiderivative(a)
[ "def", "integrate", "(", "self", ")", ":", "coeffs", "=", "self", ".", "coefficients", "(", ")", "a", ",", "b", "=", "self", ".", "domain", "(", ")", "int_coeffs", "=", "0.5", "*", "(", "b", "-", "a", ")", "*", "poly", ".", "chebyshev", ".", "chebint", "(", "coeffs", ")", "antiderivative", "=", "self", ".", "from_coeff", "(", "int_coeffs", ",", "domain", "=", "self", ".", "domain", "(", ")", ")", "return", "antiderivative", "-", "antiderivative", "(", "a", ")" ]
Return the object representing the primitive of self over the domain. The output starts at zero on the left-hand side of the domain.
[ "Return", "the", "object", "representing", "the", "primitive", "of", "self", "over", "the", "domain", ".", "The", "output", "starts", "at", "zero", "on", "the", "left", "-", "hand", "side", "of", "the", "domain", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L462-L471
8,295
CalebBell/fluids
fluids/optional/pychebfun.py
Chebfun.differentiate
def differentiate(self, n=1): """ n-th derivative, default 1. """ ak = self.coefficients() a_, b_ = self.domain() for _ in range(n): ak = self.differentiator(ak) return self.from_coeff((2./(b_-a_))**n*ak, domain=self.domain())
python
def differentiate(self, n=1): """ n-th derivative, default 1. """ ak = self.coefficients() a_, b_ = self.domain() for _ in range(n): ak = self.differentiator(ak) return self.from_coeff((2./(b_-a_))**n*ak, domain=self.domain())
[ "def", "differentiate", "(", "self", ",", "n", "=", "1", ")", ":", "ak", "=", "self", ".", "coefficients", "(", ")", "a_", ",", "b_", "=", "self", ".", "domain", "(", ")", "for", "_", "in", "range", "(", "n", ")", ":", "ak", "=", "self", ".", "differentiator", "(", "ak", ")", "return", "self", ".", "from_coeff", "(", "(", "2.", "/", "(", "b_", "-", "a_", ")", ")", "**", "n", "*", "ak", ",", "domain", "=", "self", ".", "domain", "(", ")", ")" ]
n-th derivative, default 1.
[ "n", "-", "th", "derivative", "default", "1", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L473-L481
8,296
CalebBell/fluids
fluids/optional/pychebfun.py
Chebfun.sample_function
def sample_function(self, f, N): """ Sample a function on N+1 Chebyshev points. """ x = self.interpolation_points(N+1) return f(x)
python
def sample_function(self, f, N): """ Sample a function on N+1 Chebyshev points. """ x = self.interpolation_points(N+1) return f(x)
[ "def", "sample_function", "(", "self", ",", "f", ",", "N", ")", ":", "x", "=", "self", ".", "interpolation_points", "(", "N", "+", "1", ")", "return", "f", "(", "x", ")" ]
Sample a function on N+1 Chebyshev points.
[ "Sample", "a", "function", "on", "N", "+", "1", "Chebyshev", "points", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L538-L543
8,297
CalebBell/fluids
fluids/optional/pychebfun.py
Chebfun.interpolator
def interpolator(self, x, values): """ Returns a polynomial with vector coefficients which interpolates the values at the Chebyshev points x """ # hacking the barycentric interpolator by computing the weights in advance p = Bary([0.]) N = len(values) weights = np.ones(N) weights[0] = .5 weights[1::2] = -1 weights[-1] *= .5 p.wi = weights p.xi = x p.set_yi(values) return p
python
def interpolator(self, x, values): """ Returns a polynomial with vector coefficients which interpolates the values at the Chebyshev points x """ # hacking the barycentric interpolator by computing the weights in advance p = Bary([0.]) N = len(values) weights = np.ones(N) weights[0] = .5 weights[1::2] = -1 weights[-1] *= .5 p.wi = weights p.xi = x p.set_yi(values) return p
[ "def", "interpolator", "(", "self", ",", "x", ",", "values", ")", ":", "# hacking the barycentric interpolator by computing the weights in advance", "p", "=", "Bary", "(", "[", "0.", "]", ")", "N", "=", "len", "(", "values", ")", "weights", "=", "np", ".", "ones", "(", "N", ")", "weights", "[", "0", "]", "=", ".5", "weights", "[", "1", ":", ":", "2", "]", "=", "-", "1", "weights", "[", "-", "1", "]", "*=", ".5", "p", ".", "wi", "=", "weights", "p", ".", "xi", "=", "x", "p", ".", "set_yi", "(", "values", ")", "return", "p" ]
Returns a polynomial with vector coefficients which interpolates the values at the Chebyshev points x
[ "Returns", "a", "polynomial", "with", "vector", "coefficients", "which", "interpolates", "the", "values", "at", "the", "Chebyshev", "points", "x" ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L582-L596
8,298
CalebBell/fluids
fluids/drag.py
drag_sphere
def drag_sphere(Re, Method=None, AvailableMethods=False): r'''This function handles calculation of drag coefficient on spheres. Twenty methods are available, all requiring only the Reynolds number of the sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will be automatically selected if none is specified. The full list of correlations valid for a given Reynolds number can be obtained with the `AvailableMethods` flag. If no correlation is selected, the following rules are used: * If Re < 0.01, use Stoke's solution. * If 0.01 <= Re < 0.1, linearly combine 'Barati' with Stokes's solution such that at Re = 0.1 the solution is 'Barati', and at Re = 0.01 the solution is 'Stokes'. * If 0.1 <= Re <= ~212963, use the 'Barati' solution. * If ~212963 < Re <= 1E6, use the 'Barati_high' solution. * For Re > 1E6, raises an exception; no valid results have been found. Examples -------- >>> drag_sphere(200) 0.7682237950389874 Parameters ---------- Re : float Particle Reynolds number of the sphere using the surrounding fluid density and viscosity, [-] Returns ------- Cd : float Drag coefficient [-] methods : list, only returned if AvailableMethods == True List of methods which can be used to calculate `Cd` with the given `Re` Other Parameters ---------------- Method : string, optional A string of the function name to use, as in the dictionary drag_sphere_correlations AvailableMethods : bool, optional If True, function will consider which methods which can be used to calculate `Cd` with the given `Re` ''' def list_methods(): methods = [] for key, (func, Re_min, Re_max) in drag_sphere_correlations.items(): if (Re_min is None or Re > Re_min) and (Re_max is None or Re < Re_max): methods.append(key) return methods if AvailableMethods: return list_methods() if not Method: if Re > 0.1: # Smooth transition point between the two models if Re <= 212963.26847812787: return Barati(Re) elif Re <= 1E6: return Barati_high(Re) else: raise ValueError('No models implement a solution for Re > 1E6') elif Re >= 0.01: # Re from 0.01 to 0.1 ratio = (Re - 0.01)/(0.1 - 0.01) # Ensure a smooth transition by linearly switching to Stokes' law return ratio*Barati(Re) + (1-ratio)*Stokes(Re) else: return Stokes(Re) if Method in drag_sphere_correlations: return drag_sphere_correlations[Method][0](Re) else: raise Exception('Failure in in function')
python
def drag_sphere(Re, Method=None, AvailableMethods=False): r'''This function handles calculation of drag coefficient on spheres. Twenty methods are available, all requiring only the Reynolds number of the sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will be automatically selected if none is specified. The full list of correlations valid for a given Reynolds number can be obtained with the `AvailableMethods` flag. If no correlation is selected, the following rules are used: * If Re < 0.01, use Stoke's solution. * If 0.01 <= Re < 0.1, linearly combine 'Barati' with Stokes's solution such that at Re = 0.1 the solution is 'Barati', and at Re = 0.01 the solution is 'Stokes'. * If 0.1 <= Re <= ~212963, use the 'Barati' solution. * If ~212963 < Re <= 1E6, use the 'Barati_high' solution. * For Re > 1E6, raises an exception; no valid results have been found. Examples -------- >>> drag_sphere(200) 0.7682237950389874 Parameters ---------- Re : float Particle Reynolds number of the sphere using the surrounding fluid density and viscosity, [-] Returns ------- Cd : float Drag coefficient [-] methods : list, only returned if AvailableMethods == True List of methods which can be used to calculate `Cd` with the given `Re` Other Parameters ---------------- Method : string, optional A string of the function name to use, as in the dictionary drag_sphere_correlations AvailableMethods : bool, optional If True, function will consider which methods which can be used to calculate `Cd` with the given `Re` ''' def list_methods(): methods = [] for key, (func, Re_min, Re_max) in drag_sphere_correlations.items(): if (Re_min is None or Re > Re_min) and (Re_max is None or Re < Re_max): methods.append(key) return methods if AvailableMethods: return list_methods() if not Method: if Re > 0.1: # Smooth transition point between the two models if Re <= 212963.26847812787: return Barati(Re) elif Re <= 1E6: return Barati_high(Re) else: raise ValueError('No models implement a solution for Re > 1E6') elif Re >= 0.01: # Re from 0.01 to 0.1 ratio = (Re - 0.01)/(0.1 - 0.01) # Ensure a smooth transition by linearly switching to Stokes' law return ratio*Barati(Re) + (1-ratio)*Stokes(Re) else: return Stokes(Re) if Method in drag_sphere_correlations: return drag_sphere_correlations[Method][0](Re) else: raise Exception('Failure in in function')
[ "def", "drag_sphere", "(", "Re", ",", "Method", "=", "None", ",", "AvailableMethods", "=", "False", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "for", "key", ",", "(", "func", ",", "Re_min", ",", "Re_max", ")", "in", "drag_sphere_correlations", ".", "items", "(", ")", ":", "if", "(", "Re_min", "is", "None", "or", "Re", ">", "Re_min", ")", "and", "(", "Re_max", "is", "None", "or", "Re", "<", "Re_max", ")", ":", "methods", ".", "append", "(", "key", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "if", "Re", ">", "0.1", ":", "# Smooth transition point between the two models", "if", "Re", "<=", "212963.26847812787", ":", "return", "Barati", "(", "Re", ")", "elif", "Re", "<=", "1E6", ":", "return", "Barati_high", "(", "Re", ")", "else", ":", "raise", "ValueError", "(", "'No models implement a solution for Re > 1E6'", ")", "elif", "Re", ">=", "0.01", ":", "# Re from 0.01 to 0.1", "ratio", "=", "(", "Re", "-", "0.01", ")", "/", "(", "0.1", "-", "0.01", ")", "# Ensure a smooth transition by linearly switching to Stokes' law", "return", "ratio", "*", "Barati", "(", "Re", ")", "+", "(", "1", "-", "ratio", ")", "*", "Stokes", "(", "Re", ")", "else", ":", "return", "Stokes", "(", "Re", ")", "if", "Method", "in", "drag_sphere_correlations", ":", "return", "drag_sphere_correlations", "[", "Method", "]", "[", "0", "]", "(", "Re", ")", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")" ]
r'''This function handles calculation of drag coefficient on spheres. Twenty methods are available, all requiring only the Reynolds number of the sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will be automatically selected if none is specified. The full list of correlations valid for a given Reynolds number can be obtained with the `AvailableMethods` flag. If no correlation is selected, the following rules are used: * If Re < 0.01, use Stoke's solution. * If 0.01 <= Re < 0.1, linearly combine 'Barati' with Stokes's solution such that at Re = 0.1 the solution is 'Barati', and at Re = 0.01 the solution is 'Stokes'. * If 0.1 <= Re <= ~212963, use the 'Barati' solution. * If ~212963 < Re <= 1E6, use the 'Barati_high' solution. * For Re > 1E6, raises an exception; no valid results have been found. Examples -------- >>> drag_sphere(200) 0.7682237950389874 Parameters ---------- Re : float Particle Reynolds number of the sphere using the surrounding fluid density and viscosity, [-] Returns ------- Cd : float Drag coefficient [-] methods : list, only returned if AvailableMethods == True List of methods which can be used to calculate `Cd` with the given `Re` Other Parameters ---------------- Method : string, optional A string of the function name to use, as in the dictionary drag_sphere_correlations AvailableMethods : bool, optional If True, function will consider which methods which can be used to calculate `Cd` with the given `Re`
[ "r", "This", "function", "handles", "calculation", "of", "drag", "coefficient", "on", "spheres", ".", "Twenty", "methods", "are", "available", "all", "requiring", "only", "the", "Reynolds", "number", "of", "the", "sphere", ".", "Most", "methods", "are", "valid", "from", "Re", "=", "0", "to", "Re", "=", "200", "000", ".", "A", "correlation", "will", "be", "automatically", "selected", "if", "none", "is", "specified", ".", "The", "full", "list", "of", "correlations", "valid", "for", "a", "given", "Reynolds", "number", "can", "be", "obtained", "with", "the", "AvailableMethods", "flag", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/drag.py#L1028-L1101
8,299
CalebBell/fluids
fluids/drag.py
v_terminal
def v_terminal(D, rhop, rho, mu, Method=None): r'''Calculates terminal velocity of a falling sphere using any drag coefficient method supported by `drag_sphere`. The laminar solution for Re < 0.01 is first tried; if the resulting terminal velocity does not put it in the laminar regime, a numerical solution is used. .. math:: v_t = \sqrt{\frac{4 g d_p (\rho_p-\rho_f)}{3 C_D \rho_f }} Parameters ---------- D : float Diameter of the sphere, [m] rhop : float Particle density, [kg/m^3] rho : float Density of the surrounding fluid, [kg/m^3] mu : float Viscosity of the surrounding fluid [Pa*s] Method : string, optional A string of the function name to use, as in the dictionary drag_sphere_correlations Returns ------- v_t : float Terminal velocity of falling sphere [m/s] Notes ----- As there are no correlations implemented for Re > 1E6, an error will be raised if the numerical solver seeks a solution above that limit. The laminar solution is given in [1]_ and is: .. math:: v_t = \frac{g d_p^2 (\rho_p - \rho_f)}{18 \mu_f} Examples -------- >>> v_terminal(D=70E-6, rhop=2600., rho=1000., mu=1E-3) 0.004142497244531304 Example 7-1 in GPSA handbook, 13th edition: >>> from scipy.constants import * >>> v_terminal(D=150E-6, rhop=31.2*lb/foot**3, rho=2.07*lb/foot**3, mu=1.2e-05)/foot 0.4491992020345101 The answer reported there is 0.46 ft/sec. References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Rushton, Albert, Anthony S. Ward, and Richard G. Holdich. Solid-Liquid Filtration and Separation Technology. 1st edition. Weinheim ; New York: Wiley-VCH, 1996. ''' '''The following would be the ideal implementation. The actual function is optimized for speed, not readability def err(V): Re = rho*V*D/mu Cd = Barati_high(Re) V2 = (4/3.*g*D*(rhop-rho)/rho/Cd)**0.5 return (V-V2) return fsolve(err, 1.)''' v_lam = g*D*D*(rhop-rho)/(18*mu) Re_lam = Reynolds(V=v_lam, D=D, rho=rho, mu=mu) if Re_lam < 0.01 or Method == 'Stokes': return v_lam Re_almost = rho*D/mu main = 4/3.*g*D*(rhop-rho)/rho V_max = 1E6/rho/D*mu # where the correlation breaks down, Re=1E6 def err(V): Cd = drag_sphere(Re_almost*V, Method=Method) return V - (main/Cd)**0.5 # Begin the solver with 1/100 th the velocity possible at the maximum # Reynolds number the correlation is good for return float(newton(err, V_max/100, tol=1E-12))
python
def v_terminal(D, rhop, rho, mu, Method=None): r'''Calculates terminal velocity of a falling sphere using any drag coefficient method supported by `drag_sphere`. The laminar solution for Re < 0.01 is first tried; if the resulting terminal velocity does not put it in the laminar regime, a numerical solution is used. .. math:: v_t = \sqrt{\frac{4 g d_p (\rho_p-\rho_f)}{3 C_D \rho_f }} Parameters ---------- D : float Diameter of the sphere, [m] rhop : float Particle density, [kg/m^3] rho : float Density of the surrounding fluid, [kg/m^3] mu : float Viscosity of the surrounding fluid [Pa*s] Method : string, optional A string of the function name to use, as in the dictionary drag_sphere_correlations Returns ------- v_t : float Terminal velocity of falling sphere [m/s] Notes ----- As there are no correlations implemented for Re > 1E6, an error will be raised if the numerical solver seeks a solution above that limit. The laminar solution is given in [1]_ and is: .. math:: v_t = \frac{g d_p^2 (\rho_p - \rho_f)}{18 \mu_f} Examples -------- >>> v_terminal(D=70E-6, rhop=2600., rho=1000., mu=1E-3) 0.004142497244531304 Example 7-1 in GPSA handbook, 13th edition: >>> from scipy.constants import * >>> v_terminal(D=150E-6, rhop=31.2*lb/foot**3, rho=2.07*lb/foot**3, mu=1.2e-05)/foot 0.4491992020345101 The answer reported there is 0.46 ft/sec. References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Rushton, Albert, Anthony S. Ward, and Richard G. Holdich. Solid-Liquid Filtration and Separation Technology. 1st edition. Weinheim ; New York: Wiley-VCH, 1996. ''' '''The following would be the ideal implementation. The actual function is optimized for speed, not readability def err(V): Re = rho*V*D/mu Cd = Barati_high(Re) V2 = (4/3.*g*D*(rhop-rho)/rho/Cd)**0.5 return (V-V2) return fsolve(err, 1.)''' v_lam = g*D*D*(rhop-rho)/(18*mu) Re_lam = Reynolds(V=v_lam, D=D, rho=rho, mu=mu) if Re_lam < 0.01 or Method == 'Stokes': return v_lam Re_almost = rho*D/mu main = 4/3.*g*D*(rhop-rho)/rho V_max = 1E6/rho/D*mu # where the correlation breaks down, Re=1E6 def err(V): Cd = drag_sphere(Re_almost*V, Method=Method) return V - (main/Cd)**0.5 # Begin the solver with 1/100 th the velocity possible at the maximum # Reynolds number the correlation is good for return float(newton(err, V_max/100, tol=1E-12))
[ "def", "v_terminal", "(", "D", ",", "rhop", ",", "rho", ",", "mu", ",", "Method", "=", "None", ")", ":", "'''The following would be the ideal implementation. The actual function is\n optimized for speed, not readability\n def err(V):\n Re = rho*V*D/mu\n Cd = Barati_high(Re)\n V2 = (4/3.*g*D*(rhop-rho)/rho/Cd)**0.5\n return (V-V2)\n return fsolve(err, 1.)'''", "v_lam", "=", "g", "*", "D", "*", "D", "*", "(", "rhop", "-", "rho", ")", "/", "(", "18", "*", "mu", ")", "Re_lam", "=", "Reynolds", "(", "V", "=", "v_lam", ",", "D", "=", "D", ",", "rho", "=", "rho", ",", "mu", "=", "mu", ")", "if", "Re_lam", "<", "0.01", "or", "Method", "==", "'Stokes'", ":", "return", "v_lam", "Re_almost", "=", "rho", "*", "D", "/", "mu", "main", "=", "4", "/", "3.", "*", "g", "*", "D", "*", "(", "rhop", "-", "rho", ")", "/", "rho", "V_max", "=", "1E6", "/", "rho", "/", "D", "*", "mu", "# where the correlation breaks down, Re=1E6", "def", "err", "(", "V", ")", ":", "Cd", "=", "drag_sphere", "(", "Re_almost", "*", "V", ",", "Method", "=", "Method", ")", "return", "V", "-", "(", "main", "/", "Cd", ")", "**", "0.5", "# Begin the solver with 1/100 th the velocity possible at the maximum", "# Reynolds number the correlation is good for", "return", "float", "(", "newton", "(", "err", ",", "V_max", "/", "100", ",", "tol", "=", "1E-12", ")", ")" ]
r'''Calculates terminal velocity of a falling sphere using any drag coefficient method supported by `drag_sphere`. The laminar solution for Re < 0.01 is first tried; if the resulting terminal velocity does not put it in the laminar regime, a numerical solution is used. .. math:: v_t = \sqrt{\frac{4 g d_p (\rho_p-\rho_f)}{3 C_D \rho_f }} Parameters ---------- D : float Diameter of the sphere, [m] rhop : float Particle density, [kg/m^3] rho : float Density of the surrounding fluid, [kg/m^3] mu : float Viscosity of the surrounding fluid [Pa*s] Method : string, optional A string of the function name to use, as in the dictionary drag_sphere_correlations Returns ------- v_t : float Terminal velocity of falling sphere [m/s] Notes ----- As there are no correlations implemented for Re > 1E6, an error will be raised if the numerical solver seeks a solution above that limit. The laminar solution is given in [1]_ and is: .. math:: v_t = \frac{g d_p^2 (\rho_p - \rho_f)}{18 \mu_f} Examples -------- >>> v_terminal(D=70E-6, rhop=2600., rho=1000., mu=1E-3) 0.004142497244531304 Example 7-1 in GPSA handbook, 13th edition: >>> from scipy.constants import * >>> v_terminal(D=150E-6, rhop=31.2*lb/foot**3, rho=2.07*lb/foot**3, mu=1.2e-05)/foot 0.4491992020345101 The answer reported there is 0.46 ft/sec. References ---------- .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook, Eighth Edition. McGraw-Hill Professional, 2007. .. [2] Rushton, Albert, Anthony S. Ward, and Richard G. Holdich. Solid-Liquid Filtration and Separation Technology. 1st edition. Weinheim ; New York: Wiley-VCH, 1996.
[ "r", "Calculates", "terminal", "velocity", "of", "a", "falling", "sphere", "using", "any", "drag", "coefficient", "method", "supported", "by", "drag_sphere", ".", "The", "laminar", "solution", "for", "Re", "<", "0", ".", "01", "is", "first", "tried", ";", "if", "the", "resulting", "terminal", "velocity", "does", "not", "put", "it", "in", "the", "laminar", "regime", "a", "numerical", "solution", "is", "used", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/drag.py#L1104-L1185