INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns the values needed to validate the transaction s signature_message_fragment value. | def get_signature_validation_trytes(self):
# type: () -> TryteString
"""
Returns the values needed to validate the transaction's
``signature_message_fragment`` value.
"""
return (
self.address.address
+ self.value_as_trytes
... |
Sets the is_confirmed for the bundle. | def is_confirmed(self, new_is_confirmed):
# type: (bool) -> None
"""
Sets the ``is_confirmed`` for the bundle.
"""
self._is_confirmed = new_is_confirmed
for txn in self:
txn.is_confirmed = new_is_confirmed |
Attempts to decipher encoded messages from the transactions in the bundle. | def get_messages(self, errors='drop'):
# type: (Text) -> List[Text]
"""
Attempts to decipher encoded messages from the transactions in
the bundle.
:param errors:
How to handle trytes that can't be converted, or bytes that
can't be decoded using UTF-8:
... |
Returns TryteString representations of the transactions in this bundle. | def as_tryte_strings(self, head_to_tail=False):
# type: (bool) -> List[TransactionTrytes]
"""
Returns TryteString representations of the transactions in this
bundle.
:param head_to_tail:
Determines the order of the transactions:
- ``True``: head txn firs... |
Groups transactions in the bundle by address. | def group_transactions(self):
# type: () -> List[List[Transaction]]
"""
Groups transactions in the bundle by address.
"""
groups = []
if self:
last_txn = self.tail_transaction
current_group = [last_txn]
for current_txn in self.transact... |
Automatically discover commands in the specified package. | def discover_commands(package, recursively=True):
# type: (Union[ModuleType, Text], bool) -> Dict[Text, 'CommandMeta']
"""
Automatically discover commands in the specified package.
:param package:
Package path or reference.
:param recursively:
If True, will descend recursively into sub-packages.
... |
Sends the request object to the adapter and returns the response. | def _execute(self, request):
# type: (dict) -> dict
"""
Sends the request object to the adapter and returns the response.
The command name will be automatically injected into the request
before it is sent (note: this will modify the request object).
"""
request['command'] = self.command
... |
Applies a filter to a value. If the value does not pass the filter an exception will be raised with lots of contextual info attached to it. | def _apply_filter(value, filter_, failure_message):
# type: (dict, Optional[f.BaseFilter], Text) -> dict
"""
Applies a filter to a value. If the value does not pass the
filter, an exception will be raised with lots of contextual info
attached to it.
"""
if filter_:
runner = f.FilterRu... |
Returns the URL to check job status. | def get_jobs_url(self, job_id):
# type: (Text) -> Text
"""
Returns the URL to check job status.
:param job_id:
The ID of the job to check.
"""
return compat.urllib_parse.urlunsplit((
self.uri.scheme,
self.uri.netloc,
self.u... |
Returns all errors found with the bundle. | def errors(self):
# type: () -> List[Text]
"""
Returns all errors found with the bundle.
"""
try:
self._errors.extend(self._validator) # type: List[Text]
except StopIteration:
pass
return self._errors |
Returns whether the bundle is valid. | def is_valid(self):
# type: () -> bool
"""
Returns whether the bundle is valid.
"""
if not self._errors:
try:
# We only have to check for a single error to determine
# if the bundle is valid or not.
self._errors.append(n... |
Creates a generator that does all the work. | def _create_validator(self):
# type: () -> Generator[Text, None, None]
"""
Creates a generator that does all the work.
"""
# Group transactions by address to make it easier to iterate
# over inputs.
grouped_transactions = self.bundle.group_transactions()
... |
Validates the signature fragments in the bundle. | def _get_bundle_signature_errors(self, groups):
# type: (List[List[Transaction]]) -> List[Text]
"""
Validates the signature fragments in the bundle.
:return:
List of error messages.
If empty, signature fragments are valid.
"""
# Start with the cur... |
Validates the signature fragments for a group of transactions using the specified sponge type. | def _get_group_signature_error(group, sponge_type):
# type: (List[Transaction], type) -> Optional[Text]
"""
Validates the signature fragments for a group of transactions
using the specified sponge type.
Note: this method assumes that the transactions in the group
have al... |
Recursively traverse the Tangle collecting transactions until we hit a new bundle. | def _traverse_bundle(self, txn_hash, target_bundle_hash=None):
# type: (TransactionHash, Optional[BundleHash]) -> List[Transaction]
"""
Recursively traverse the Tangle, collecting transactions until
we hit a new bundle.
This method is (usually) faster than ``findTransactions``, ... |
Starts the REPL. | def _start_repl(api):
# type: (Iota) -> None
"""
Starts the REPL.
"""
banner = (
'IOTA API client for {uri} ({testnet}) '
'initialized as variable `api`.\n'
'Type `help(api)` for list of API commands.'.format(
testnet='testnet' ... |
Generates a random seed using a CSPRNG. | def random(cls, length=Hash.LEN):
"""
Generates a random seed using a CSPRNG.
:param length:
Length of seed, in trytes.
For maximum security, this should always be set to 81, but
you can change it if you're 110% sure you know what you're
doing.
... |
Generates the digest used to do the actual signing. | def get_digest(self):
# type: () -> Digest
"""
Generates the digest used to do the actual signing.
Signing keys can have variable length and tend to be quite long,
which makes them not-well-suited for use in crypto algorithms.
The digest is essentially the result of run... |
Signs the inputs starting at the specified index. | def sign_input_transactions(self, bundle, start_index):
# type: (Bundle, int) -> None
"""
Signs the inputs starting at the specified index.
:param bundle:
The bundle that contains the input transactions to sign.
:param start_index:
The index of the first... |
Makes JSON - serializable objects play nice with IPython s default pretty - printer. | def _repr_pretty_(self, p, cycle):
"""
Makes JSON-serializable objects play nice with IPython's default
pretty-printer.
Sadly, :py:func:`pprint.pprint` does not have a similar
mechanism.
References:
- http://ipython.readthedocs.io/en/stable/api/generated/IPytho... |
Absorb trits into the sponge from a buffer. | def absorb(self, trits, offset=0, length=None):
# type: (MutableSequence[int], int, Optional[int]) -> None
"""
Absorb trits into the sponge from a buffer.
:param trits:
Buffer that contains the trits to absorb.
:param offset:
Starting offset in ``trits``... |
Squeeze trits from the sponge into a buffer. | def squeeze(self, trits, offset=0, length=None):
# type: (MutableSequence[int], int, Optional[int]) -> None
"""
Squeeze trits from the sponge into a buffer.
:param trits:
Buffer that will hold the squeezed trits.
IMPORTANT: If ``trits`` is too small, it will be... |
Attaches a context value to an Exception. | def with_context(exc, context):
# type: (Exception, dict) -> Exception
"""
Attaches a ``context`` value to an Exception.
Before:
.. code-block:: python
exc = Exception('Frog blast the vent core!')
exc.context = { ... }
raise exc
After:
.. code-block:: python
... |
Generates a filter chain for validating a security level. | def SecurityLevel():
"""
Generates a filter chain for validating a security level.
"""
return (
f.Type(int) |
f.Min(1) |
f.Max(3) |
f.Optional(default=AddressGenerator.DEFAULT_SECURITY_LEVEL)
) |
Returns a TryteString representation of the transaction. | def as_tryte_string(self):
# type: () -> TryteString
"""
Returns a TryteString representation of the transaction.
"""
if not self.bundle_hash:
raise with_context(
exc=RuntimeError(
'Cannot get TryteString representation of {cls} ins... |
Increments the transaction s legacy tag used to fix insecure bundle hashes when finalizing a bundle. | def increment_legacy_tag(self):
"""
Increments the transaction's legacy tag, used to fix insecure
bundle hashes when finalizing a bundle.
References:
- https://github.com/iotaledger/iota.lib.py/issues/84
"""
self._legacy_tag = (
Tag.from_trits(add_tr... |
Determines the most relevant tag for the bundle. | def tag(self):
# type: () -> Tag
"""
Determines the most relevant tag for the bundle.
"""
for txn in reversed(self): # type: ProposedTransaction
if txn.tag:
return txn.tag
return Tag(b'') |
Adds a transaction to the bundle. | def add_transaction(self, transaction):
# type: (ProposedTransaction) -> None
"""
Adds a transaction to the bundle.
If the transaction message is too long, it will be split
automatically into multiple transactions.
"""
if self.hash:
raise RuntimeError... |
Adds inputs to spend in the bundle. | def add_inputs(self, inputs):
# type: (Iterable[Address]) -> None
"""
Adds inputs to spend in the bundle.
Note that each input may require multiple transactions, in order
to hold the entire signature.
:param inputs:
Addresses to use as the inputs for this bu... |
Finalizes the bundle preparing it to be attached to the Tangle. | def finalize(self):
# type: () -> None
"""
Finalizes the bundle, preparing it to be attached to the Tangle.
"""
if self.hash:
raise RuntimeError('Bundle is already finalized.')
if not self:
raise ValueError('Bundle has no transactions.')
... |
Sign inputs in a finalized bundle. | def sign_inputs(self, key_generator):
# type: (KeyGenerator) -> None
"""
Sign inputs in a finalized bundle.
"""
if not self.hash:
raise RuntimeError('Cannot sign inputs until bundle is finalized.')
# Use a counter for the loop so that we can skip ahead as we ... |
Signs the input at the specified index. | def sign_input_at(self, start_index, private_key):
# type: (int, PrivateKey) -> None
"""
Signs the input at the specified index.
:param start_index:
The index of the first input transaction.
If necessary, the resulting signature will be split across
... |
Creates transactions for the specified input address. | def _create_input_transactions(self, addy):
# type: (Address) -> None
"""
Creates transactions for the specified input address.
"""
self._transactions.append(ProposedTransaction(
address=addy,
tag=self.tag,
# Spend the entire address balance; ... |
Converts between any two standard units of iota. | def convert_value_to_standard_unit(value, symbol='i'):
# type: (Text, Text) -> float
"""
Converts between any two standard units of iota.
:param value:
Value (affixed) to convert. For example: '1.618 Mi'.
:param symbol:
Unit symbol of iota to convert to. For example: 'Gi'.
:re... |
modular_squareroot_in_FQ2 ( x ) returns the value y such that y ** 2 % q == x and None if this is not possible. In cases where there are two solutions the value with higher imaginary component is favored ; if both solutions have equal imaginary component the value with higher real component is favored. | def modular_squareroot_in_FQ2(value: FQ2) -> FQ2:
"""
``modular_squareroot_in_FQ2(x)`` returns the value ``y`` such that ``y**2 % q == x``,
and None if this is not possible. In cases where there are two solutions,
the value with higher imaginary component is favored;
if both solutions have equal ima... |
A compressed point is a 384 - bit integer with the bit order ( c_flag b_flag a_flag x ) where the c_flag bit is always set to 1 the b_flag bit indicates infinity when set to 1 the a_flag bit helps determine the y - coordinate when decompressing and the 381 - bit integer x is the x - coordinate of the point. | def compress_G1(pt: G1Uncompressed) -> G1Compressed:
"""
A compressed point is a 384-bit integer with the bit order (c_flag, b_flag, a_flag, x),
where the c_flag bit is always set to 1,
the b_flag bit indicates infinity when set to 1,
the a_flag bit helps determine the y-coordinate when decompressin... |
Recovers x and y coordinates from the compressed point. | def decompress_G1(z: G1Compressed) -> G1Uncompressed:
"""
Recovers x and y coordinates from the compressed point.
"""
# b_flag == 1 indicates the infinity point
b_flag = (z % POW_2_383) // POW_2_382
if b_flag == 1:
return Z1
x = z % POW_2_381
# Try solving y coordinate from the ... |
The compressed point ( z1 z2 ) has the bit order: z1: ( c_flag1 b_flag1 a_flag1 x1 ) z2: ( c_flag2 b_flag2 a_flag2 x2 ) where - c_flag1 is always set to 1 - b_flag1 indicates infinity when set to 1 - a_flag1 helps determine the y - coordinate when decompressing - a_flag2 b_flag2 and c_flag2 are always set to 0 | def compress_G2(pt: G2Uncompressed) -> G2Compressed:
"""
The compressed point (z1, z2) has the bit order:
z1: (c_flag1, b_flag1, a_flag1, x1)
z2: (c_flag2, b_flag2, a_flag2, x2)
where
- c_flag1 is always set to 1
- b_flag1 indicates infinity when set to 1
- a_flag1 helps determine the y-... |
Recovers x and y coordinates from the compressed point ( z1 z2 ). | def decompress_G2(p: G2Compressed) -> G2Uncompressed:
"""
Recovers x and y coordinates from the compressed point (z1, z2).
"""
z1, z2 = p
# b_flag == 1 indicates the infinity point
b_flag1 = (z1 % POW_2_383) // POW_2_382
if b_flag1 == 1:
return Z2
x1 = z1 % POW_2_381
x2 = z... |
Extended euclidean algorithm to find modular inverses for integers | def prime_field_inv(a: int, n: int) -> int:
"""
Extended euclidean algorithm to find modular inverses for integers
"""
if a == 0:
return 0
lm, hm = 1, 0
low, high = a % n, n
while low > 1:
r = high // low
nm, new = hm - lm * r, high - low * r
lm, low, hm, high... |
Load a lexicon from a JSON file. | def from_json_file(cls, filename):
"""
Load a lexicon from a JSON file.
Args:
filename (str): The path to a JSON dump.
"""
with open(filename, 'r') as fp:
return cls(json.load(fp)) |
Given a string and a category finds and combines words into groups based on their proximity. | def find_word_groups(self, text, category, proximity=2):
"""
Given a string and a category, finds and combines words into
groups based on their proximity.
Args:
text (str): Some text.
tokens (list): A list of regex strings.
Returns:
list. The... |
Given a string and a dict of synonyms returns the preferred word. Case insensitive. | def find_synonym(self, word):
"""
Given a string and a dict of synonyms, returns the 'preferred'
word. Case insensitive.
Args:
word (str): A word.
Returns:
str: The preferred word, or the input word if not found.
Example:
>>> syn = {... |
Parse a piece of text and replace any abbreviations with their full word equivalents. Uses the lexicon. abbreviations dictionary to find abbreviations. | def expand_abbreviations(self, text):
"""
Parse a piece of text and replace any abbreviations with their full
word equivalents. Uses the lexicon.abbreviations dictionary to find
abbreviations.
Args:
text (str): The text to parse.
Returns:
str: Th... |
Takes a piece of text representing a lithologic description for one component e. g. Red vf - f sandstone and turns it into a dictionary of attributes. | def get_component(self, text, required=False, first_only=True):
"""
Takes a piece of text representing a lithologic description for one
component, e.g. "Red vf-f sandstone" and turns it into a dictionary
of attributes.
TODO:
Generalize this so that we can use any typ... |
Split a description into parts each of which can be turned into a single component. | def split_description(self, text):
"""
Split a description into parts, each of which can be turned into
a single component.
"""
# Protect some special sequences.
t = re.sub(r'(\d) ?in\. ', r'\1 inch ', text) # Protect.
t = re.sub(r'(\d) ?ft\. ', r'\1 feet ', t) ... |
Lists the categories in the lexicon except the optional categories. | def categories(self):
"""
Lists the categories in the lexicon, except the
optional categories.
Returns:
list: A list of strings of category names.
"""
keys = [k for k in self.__dict__.keys() if k not in SPECIAL]
return keys |
Jupyter Notebook magic repr function. | def _repr_html_(self):
"""
Jupyter Notebook magic repr function.
"""
rows, c = '', ''
s = '<tr><td><strong>{k}</strong></td><td style="{stl}">{v}</td></tr>'
for k, v in self.__dict__.items():
if k == '_colour':
k = 'colour'
c =... |
Jupyter Notebook magic repr function as a row – used by Legend. _repr_html_ (). | def _repr_html_row_(self, keys):
"""
Jupyter Notebook magic repr function as a row – used by
``Legend._repr_html_()``.
"""
tr, th, c = '', '', ''
r = '<td style="{stl}">{v}</td>'
h = '<th>{k}</th>'
for k in keys:
v = self.__dict__.get(k)
... |
Returns a minimal Decor with a random colour. | def random(cls, component):
"""
Returns a minimal Decor with a random colour.
"""
colour = random.sample([i for i in range(256)], 3)
return cls({'colour': colour, 'component': component, 'width': 1.0}) |
Make a simple plot of the Decor. | def plot(self, fmt=None, fig=None, ax=None):
"""
Make a simple plot of the Decor.
Args:
fmt (str): A Python format string for the component summaries.
fig (Pyplot figure): A figure, optional. Use either fig or ax, not
both.
ax (Pyplot axis): A... |
Jupyter Notebook magic repr function. | def _repr_html_(self):
"""
Jupyter Notebook magic repr function.
"""
all_keys = list(set(itertools.chain(*[d.keys for d in self])))
rows = ''
for decor in self:
th, tr = decor._repr_html_row_(keys=all_keys)
rows += '<tr>{}</tr>'.format(tr)
... |
Generate a default legend. | def builtin(cls, name):
"""
Generate a default legend.
Args:
name (str): The name of the legend you want. Not case sensitive.
'nsdoe': Nova Scotia Dept. of Energy
'canstrat': Canstrat
'nagmdm__6_2': USGS N. Am. Geol. Map Data Model ... |
Generate a default timescale legend. No arguments. | def builtin_timescale(cls, name):
"""
Generate a default timescale legend. No arguments.
Returns:
Legend: The timescale stored in `defaults.py`.
"""
names = {
'isc': TIMESCALE__ISC,
'usgs_isc': TIMESCALE__USGS_ISC,
'... |
Generate a random legend for a given list of components. | def random(cls, components, width=False, colour=None):
"""
Generate a random legend for a given list of components.
Args:
components (list or Striplog): A list of components. If you pass
a Striplog, it will use the primary components. If you pass a
co... |
A slightly easier way to make legends from images. | def from_image(cls, filename, components,
ignore=None,
col_offset=0.1,
row_offset=2):
"""
A slightly easier way to make legends from images.
Args:
filename (str)
components (list)
ignore (list): Colours... |
Read CSV text and generate a Legend. | def from_csv(cls, filename=None, text=None):
"""
Read CSV text and generate a Legend.
Args:
string (str): The CSV string.
In the first row, list the properties. Precede the properties of the
component with 'comp ' or 'component '. For example:
colour, widt... |
Renders a legend as a CSV string. | def to_csv(self):
"""
Renders a legend as a CSV string.
No arguments.
Returns:
str: The legend as a CSV.
"""
# We can't delegate this to Decor because we need to know the superset
# of all Decor properties. There may be lots of blanks.
header... |
The maximum width of all the Decors in the Legend. This is needed to scale a Legend or Striplog when plotting with widths turned on. | def max_width(self):
"""
The maximum width of all the Decors in the Legend. This is needed
to scale a Legend or Striplog when plotting with widths turned on.
"""
try:
maximum = max([row.width for row in self.__list if row.width is not None])
return maximum... |
Get the decor for a component. | def get_decor(self, c, match_only=None):
"""
Get the decor for a component.
Args:
c (component): The component to look up.
match_only (list of str): The component attributes to include in the
comparison. Default: All of them.
Returns:
Dec... |
Get the attribute of a component. | def getattr(self, c, attr, default=None, match_only=None):
"""
Get the attribute of a component.
Args:
c (component): The component to look up.
attr (str): The attribute to get.
default (str): What to return in the event of no match.
match_only (list ... |
Get the display colour of a component. Wraps getattr (). | def get_colour(self, c, default='#eeeeee', match_only=None):
"""
Get the display colour of a component. Wraps `getattr()`.
Development note:
Cannot define this as a `partial()` because I want
to maintain the order of arguments in `getattr()`.
Args:
c ... |
Get the display width of a component. Wraps getattr (). | def get_width(self, c, default=0, match_only=None):
"""
Get the display width of a component. Wraps `getattr()`.
Development note: Cannot define this as a `partial()` because I want
to maintain the order of arguments in `getattr()`.
Args:
c (component): The componen... |
Get the component corresponding to a display colour. This is for generating a Striplog object from a colour image of a striplog. | def get_component(self, colour, tolerance=0, default=None):
"""
Get the component corresponding to a display colour. This is for
generating a Striplog object from a colour image of a striplog.
Args:
colour (str): The hex colour string to look up.
tolerance (float):... |
Make a simple plot of the legend. | def plot(self, fmt=None):
"""
Make a simple plot of the legend.
Simply calls Decor.plot() on all of its members.
TODO: Build a more attractive plot.
"""
for d in self.__list:
d.plot(fmt=fmt)
return None |
Jupyter Notebook magic repr function. | def _repr_html_(self):
"""
Jupyter Notebook magic repr function.
"""
rows = ''
s = '<tr><td><strong>{k}</strong></td><td>{v}</td></tr>'
for k, v in self.__dict__.items():
rows += s.format(k=k, v=v)
html = '<table>{}</table>'.format(rows)
return... |
Generate a Component from a text string using a Lexicon. | def from_text(cls, text, lexicon, required=None, first_only=True):
"""
Generate a Component from a text string, using a Lexicon.
Args:
text (str): The text string to parse.
lexicon (Lexicon): The dictionary to use for the
categories and lexemes.
... |
Given a format string return a summary description of a component. | def summary(self, fmt=None, initial=True, default=''):
"""
Given a format string, return a summary description of a component.
Args:
component (dict): A component dictionary.
fmt (str): Describes the format with a string. If no format is
given, you will j... |
Graceful deprecation for old class name. | def Rock(*args, **kwargs):
"""
Graceful deprecation for old class name.
"""
with warnings.catch_warnings():
warnings.simplefilter("always")
w = "The 'Rock' class was renamed 'Component'. "
w += "Please update your code."
warnings.warn(w, DeprecationWarning, stacklevel=2)... |
Processes a single row from the file. | def _process_row(text, columns):
"""
Processes a single row from the file.
"""
if not text:
return
# Construct the column dictionary that maps each field to
# its start, its length, and its read and write functions.
coldict = {k: {'start': s,
'len': l,
... |
Read all the rows and return a dict of the results. | def parse_canstrat(text):
"""
Read all the rows and return a dict of the results.
"""
result = {}
for row in text.split('\n'):
if not row:
continue
if len(row) < 8: # Not a real record.
continue
# Read the metadata for this row/
row_header =... |
Still unsure about best way to do this hence cruft. | def get_template(name):
"""
Still unsure about best way to do this, hence cruft.
"""
text = re.sub(r'\r\n', r'\n', name)
text = re.sub(r'\{([FISDE°].*?)\}', r'{{\1}}', text)
return text |
Private method. Checks if striplog is monotonically increasing in depth. | def __strict(self):
"""
Private method. Checks if striplog is monotonically increasing in
depth.
Returns:
Bool.
"""
def conc(a, b):
return a + b
# Check boundaries, b
b = np.array(reduce(conc, [[i.top.z, i.base.z] for i in self]))... |
Property. Summarize a Striplog with some statistics. | def unique(self):
"""
Property. Summarize a Striplog with some statistics.
Returns:
List. A list of (Component, total thickness thickness) tuples.
"""
all_rx = set([iv.primary for iv in self])
table = {r: 0 for r in all_rx}
for iv in self:
... |
Property. | def top(self):
"""
Property.
"""
# For backwards compatibility.
with warnings.catch_warnings():
warnings.simplefilter("always")
w = "Striplog.top is deprecated; please use Striplog.unique"
warnings.warn(w, DeprecationWarning, stacklevel=2)
... |
Private method. Take a sequence of tops in an arbitrary dimension and provide a list of intervals from which a striplog can be made. | def __intervals_from_tops(self,
tops,
values,
basis,
components,
field=None,
ignore_nan=True):
"""
Private method. Take a se... |
Private function. Make sure we have what we need to make a striplog. | def _clean_longitudinal_data(cls, data, null=None):
"""
Private function. Make sure we have what we need to make a striplog.
"""
# Rename 'depth' or 'MD'
if ('top' not in data.keys()):
data['top'] = data.pop('depth', data.pop('MD', None))
# Sort everything
... |
Makes a striplog from a Petrel text file. | def from_petrel(cls, filename,
stop=None,
points=False,
null=None,
function=None,
include=None,
exclude=None,
remap=None,
ignore=None):
"""
Mak... |
Private function. Takes a data dictionary and reconstructs a list of Intervals from it. | def _build_list_of_Intervals(cls,
data_dict,
stop=None,
points=False,
include=None,
exclude=None,
ignore=None,
... |
Load from a CSV file or text. | def from_csv(cls, filename=None,
text=None,
dlm=',',
lexicon=None,
points=False,
include=None,
exclude=None,
remap=None,
function=None,
null=None,
ign... |
Convert a CSV string into a striplog. Expects 2 or 3 fields: top description OR top base description | def from_descriptions(cls, text,
lexicon=None,
source='CSV',
dlm=',',
points=False,
abbreviations=False,
complete=False,
order='depth',
... |
Read an image and generate Striplog. | def from_image(cls, filename, start, stop, legend,
source="Image",
col_offset=0.1,
row_offset=2,
tolerance=0):
"""
Read an image and generate Striplog.
Args:
filename (str): An image file, preferably high-re... |
For backwards compatibility. | def from_img(cls, *args, **kwargs):
"""
For backwards compatibility.
"""
with warnings.catch_warnings():
warnings.simplefilter("always")
w = "from_img() is deprecated; please use from_image()"
warnings.warn(w)
return cls.from_image(*args, **kwa... |
DEPRECATING. | def _from_array(cls, a,
lexicon=None,
source="",
points=False,
abbreviations=False):
"""
DEPRECATING.
Turn an array-like into a Striplog. It should have the following
format (where ``base`` is optional):
... |
Turn a 1D array into a striplog given a cutoff. | def from_log(cls, log,
cutoff=None,
components=None,
legend=None,
legend_field=None,
field=None,
right=False,
basis=None,
source='Log'):
"""
Turn a 1D array into a stri... |
Turn LAS3 lithology section into a Striplog. | def from_las3(cls, string, lexicon=None,
source="LAS",
dlm=',',
abbreviations=False):
"""
Turn LAS3 'lithology' section into a Striplog.
Args:
string (str): A section from an LAS3 file.
lexicon (Lexicon): The language... |
Eat a Canstrat DAT file and make a striplog. | def from_canstrat(cls, filename, source='canstrat'):
"""
Eat a Canstrat DAT file and make a striplog.
"""
with open(filename) as f:
dat = f.read()
data = parse_canstrat(dat)
list_of_Intervals = []
for d in data[7]: # 7 is the 'card type' for litholo... |
Returns a shallow copy. | def copy(self):
"""Returns a shallow copy."""
return Striplog([i.copy() for i in self],
order=self.order,
source=self.source) |
Returns a CSV string built from the summaries of the Intervals. | def to_csv(self,
filename=None,
as_text=True,
use_descriptions=False,
dlm=",",
header=True):
"""
Returns a CSV string built from the summaries of the Intervals.
Args:
use_descriptions (bool): Whether to use d... |
Returns an LAS 3. 0 section string. | def to_las3(self, use_descriptions=False, dlm=",", source="Striplog"):
"""
Returns an LAS 3.0 section string.
Args:
use_descriptions (bool): Whether to use descriptions instead
of summaries, if available.
dlm (str): The delimiter.
source (str)... |
Return a fully sampled log from a striplog. Useful for crossplotting with log data for example. | def to_log(self,
step=1.0,
start=None,
stop=None,
basis=None,
field=None,
field_function=None,
dtype=None,
table=None,
legend=None,
legend_field=None,
matc... |
Plotting but only for points ( as opposed to intervals ). | def plot_points(self, ax,
legend=None,
field=None,
field_function=None,
undefined=0,
**kwargs):
"""
Plotting, but only for points (as opposed to intervals).
"""
ys = [iv.top.z for iv in s... |
Plotting but only for tops ( as opposed to intervals ). | def plot_tops(self, ax, legend=None, field=None, **kwargs):
"""
Plotting, but only for tops (as opposed to intervals).
"""
if field is None:
raise StriplogError('You must provide a field to plot.')
ys = [iv.top.z for iv in self]
try:
try:
... |
Plotting but only for tops ( as opposed to intervals ). | def plot_field(self, ax, legend=None, field=None, **kwargs):
"""
Plotting, but only for tops (as opposed to intervals).
"""
if field is None:
raise StriplogError('You must provide a field to plot.')
try:
try:
xs = [getattr(iv.primary, fiel... |
Plotting but only the Rectangles. You have to set up the figure. Returns a matplotlib axis object. | def plot_axis(self,
ax,
legend,
ladder=False,
default_width=1,
match_only=None,
colour=None,
colour_function=None,
cmap=None,
default=None,
... |
Get data from the striplog. | def get_data(self, field, function=None, default=None):
"""
Get data from the striplog.
"""
f = function or utils.null
data = []
for iv in self:
d = iv.data.get(field)
if d is None:
if default is not None:
d = de... |
Hands - free plotting. | def plot(self,
legend=None,
width=1.5,
ladder=True,
aspect=10,
ticks=(1, 10),
match_only=None,
ax=None,
return_fig=False,
colour=None,
cmap='viridis',
default=None,
... |
Get the index of the interval at a particular depth ( though this might be an elevation or age or anything ). | def read_at(self, d, index=False):
"""
Get the index of the interval at a particular 'depth' (though this
might be an elevation or age or anything).
Args:
d (Number): The 'depth' to query.
index (bool): Whether to return the index instead of the interval.
... |
For backwards compatibility. | def depth(self, d):
"""
For backwards compatibility.
"""
with warnings.catch_warnings():
warnings.simplefilter("always")
w = "depth() is deprecated; please use read_at()"
warnings.warn(w)
return self.read_at(d) |
Extract a log into the components of a striplog. | def extract(self, log, basis, name, function=None):
"""
'Extract' a log into the components of a striplog.
Args:
log (array_like). A log or other 1D data.
basis (array_like). The depths or elevations of the log samples.
name (str). The name of the attribute t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.