sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def start_inline(self,stylestack=None): """ starts an inline entity with an optional style definition """ self.stack.append('inline') if self.dirty: self.escpos._raw(' ') if stylestack: self.style(stylestack)
starts an inline entity with an optional style definition
entailment
def start_block(self,stylestack=None): """ starts a block entity with an optional style definition """ if self.dirty: self.escpos._raw('\n') self.dirty = False self.stack.append('block') if stylestack: self.style(stylestack)
starts a block entity with an optional style definition
entailment
def end_entity(self): """ ends the entity definition. (but does not cancel the active style!) """ if self.stack[-1] == 'block' and self.dirty: self.escpos._raw('\n') self.dirty = False if len(self.stack) > 1: self.stack = self.stack[:-1]
ends the entity definition. (but does not cancel the active style!)
entailment
def pre(self,text): """ puts a string of text in the entity keeping the whitespace intact """ if text: self.escpos.text(text) self.dirty = True
puts a string of text in the entity keeping the whitespace intact
entailment
def text(self,text): """ puts text in the entity. Whitespace and newlines are stripped to single spaces. """ if text: text = utfstr(text) text = text.strip() text = re.sub('\s+',' ',text) if text: self.dirty = True self.escp...
puts text in the entity. Whitespace and newlines are stripped to single spaces.
entailment
def _check_image_size(self, size): """ Check and fix the size of the image to 32 bits """ if size % 32 == 0: return (0, 0) else: image_border = 32 - (size % 32) if (image_border % 2) == 0: return (image_border / 2, image_border / 2) ...
Check and fix the size of the image to 32 bits
entailment
def _print_image(self, line, size): """ Print formatted image """ i = 0 cont = 0 buffer = "" self._raw(S_RASTER_N) buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1], 0) self._raw(buffer.decode('hex')) buffer = "" while i < ...
Print formatted image
entailment
def _raw_print_image(self, line, size, output=None ): """ Print formatted image """ i = 0 cont = 0 buffer = "" raw = "" def __raw(string): if output: output(string) else: self._raw(string) raw += S_R...
Print formatted image
entailment
def _convert_image(self, im): """ Parse image and prepare it to a printable format """ pixels = [] pix_line = "" im_left = "" im_right = "" switch = 0 img_size = [ 0, 0 ] if im.size[0] > 512: print "WARNING: Image is wider than 512 and ...
Parse image and prepare it to a printable format
entailment
def image(self,path_img): """ Open image file """ im_open = Image.open(path_img) im = im_open.convert("RGB") # Convert the RGB image in printable image pix_line, img_size = self._convert_image(im) self._print_image(pix_line, img_size)
Open image file
entailment
def qr(self,text): """ Print QR Code for the provided string """ qr_code = qrcode.QRCode(version=4, box_size=4, border=1) qr_code.add_data(text) qr_code.make(fit=True) qr_img = qr_code.make_image() im = qr_img._img.convert("RGB") # Convert the RGB image in printab...
Print QR Code for the provided string
entailment
def barcode(self, code, bc, width=255, height=2, pos='below', font='a'): """ Print Barcode """ # Align Bar Code() self._raw(TXT_ALIGN_CT) # Height if height >=2 or height <=6: self._raw(BARCODE_HEIGHT) else: raise BarcodeSizeError() # Width...
Print Barcode
entailment
def receipt(self,xml): """ Prints an xml based receipt definition """ def strclean(string): if not string: string = '' string = string.strip() string = re.sub('\s+',' ',string) return string def format_value(value,...
Prints an xml based receipt definition
entailment
def text(self,txt): """ Print Utf8 encoded alpha-numeric text """ if not txt: return try: txt = txt.decode('utf-8') except: try: txt = txt.decode('utf-16') except: pass self.extra_chars = 0 ...
Print Utf8 encoded alpha-numeric text
entailment
def set(self, align='left', font='a', type='normal', width=1, height=1): """ Set text properties """ # Align if align.upper() == "CENTER": self._raw(TXT_ALIGN_CT) elif align.upper() == "RIGHT": self._raw(TXT_ALIGN_RT) elif align.upper() == "LEFT": ...
Set text properties
entailment
def cut(self, mode=''): """ Cut paper """ # Fix the size between last line and cut # TODO: handle this with a line feed self._raw("\n\n\n\n\n\n") if mode.upper() == "PART": self._raw(PAPER_PART_CUT) else: # DEFAULT MODE: FULL CUT self._raw(PAPER_FU...
Cut paper
entailment
def cashdraw(self, pin): """ Send pulse to kick the cash drawer """ if pin == 2: self._raw(CD_KICK_2) elif pin == 5: self._raw(CD_KICK_5) else: raise CashDrawerError()
Send pulse to kick the cash drawer
entailment
def hw(self, hw): """ Hardware operations """ if hw.upper() == "INIT": self._raw(HW_INIT) elif hw.upper() == "SELECT": self._raw(HW_SELECT) elif hw.upper() == "RESET": self._raw(HW_RESET) else: # DEFAULT: DOES NOTHING pass
Hardware operations
entailment
def control(self, ctl): """ Feed control sequences """ if ctl.upper() == "LF": self._raw(CTL_LF) elif ctl.upper() == "FF": self._raw(CTL_FF) elif ctl.upper() == "CR": self._raw(CTL_CR) elif ctl.upper() == "HT": self._raw(CTL_HT) ...
Feed control sequences
entailment
def open(self): """ Search device on USB tree and set is as escpos device """ self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct) if self.device is None: raise NoDeviceError() try: if self.device.is_kernel_driver_active(self.inte...
Search device on USB tree and set is as escpos device
entailment
def _raw(self, msg): """ Print any command sent in raw format """ if len(msg) != self.device.write(self.out_ep, msg, self.interface): self.device.write(self.out_ep, self.errorText, self.interface) raise TicketNotPrinted()
Print any command sent in raw format
entailment
def open(self): """ Setup serial port and set is as escpos device """ self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=self.timeout, dsrdtr=True) if self.device is not None: ...
Setup serial port and set is as escpos device
entailment
def open(self): """ Open TCP socket and set it as escpos device """ self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.device.connect((self.host, self.port)) if self.device is None: print "Could not open socket for %s" % self.host
Open TCP socket and set it as escpos device
entailment
def _pinyin_generator(chars, format): """Generate pinyin for chars, if char is not chinese character, itself will be returned. Chars must be unicode list. """ for char in chars: key = "%X" % ord(char) pinyin = pinyin_dict.get(key, char) tone = pinyin_tone.get(key, 0) ...
Generate pinyin for chars, if char is not chinese character, itself will be returned. Chars must be unicode list.
entailment
def get(s, delimiter='', format="diacritical"): """Return pinyin of string, the string must be unicode """ return delimiter.join(_pinyin_generator(u(s), format=format))
Return pinyin of string, the string must be unicode
entailment
def get_initial(s, delimiter=' '): """Return the 1st char of pinyin of string, the string must be unicode """ initials = (p[0] for p in _pinyin_generator(u(s), format="strip")) return delimiter.join(initials)
Return the 1st char of pinyin of string, the string must be unicode
entailment
def _add_to_tree(tree, word, meaning): ''' We build word search trees, where we walk down the letters of a word. For example: 你 Good 你好 Hello Would build the tree 你 / \ You 好 \ Hello ''' if len(word) == 0: tree[''] = meaning ...
We build word search trees, where we walk down the letters of a word. For example: 你 Good 你好 Hello Would build the tree 你 / \ You 好 \ Hello
entailment
def init(): ''' Load in the Chinese-English dictionary. This takes 1-2 seconds. It is done when the other functions are used, but this is public since preloading sometimes makes sense. ''' global dictionaries, trees dictionaries = { 'traditional': {}, 'simplified': {} } ...
Load in the Chinese-English dictionary. This takes 1-2 seconds. It is done when the other functions are used, but this is public since preloading sometimes makes sense.
entailment
def translate_word(word, dictionary=['simplified']): ''' Return the set of translations for a single character or word, if available. ''' if not dictionaries: init() for d in dictionary: if word in dictionaries[d]: return dictionaries[d][word] return None
Return the set of translations for a single character or word, if available.
entailment
def _words_at_the_beginning(word, tree, prefix=""): ''' We return all portions of the tree corresponding to the beginning of `word`. This is used recursively, so we pass the prefix so we can return meaningful words+translations. ''' l = [] if "" in tree: l.append([prefix, tree[""]]) ...
We return all portions of the tree corresponding to the beginning of `word`. This is used recursively, so we pass the prefix so we can return meaningful words+translations.
entailment
def all_phrase_translations(phrase): ''' Return the set of translations for all possible words in a full phrase. Chinese is sometimes ambiguous. We do not attempt to disambiguate, or handle unknown letters especially well. Full parsing is left to upstream logic. ''' if not trees: ini...
Return the set of translations for all possible words in a full phrase. Chinese is sometimes ambiguous. We do not attempt to disambiguate, or handle unknown letters especially well. Full parsing is left to upstream logic.
entailment
def process(self, instance, force=False): """Processing is triggered by field's pre_save method. It will be executed if field's value has been changed (known through descriptor and stashing logic) or if model instance has never been saved before, i.e. no pk set, because there is a chance...
Processing is triggered by field's pre_save method. It will be executed if field's value has been changed (known through descriptor and stashing logic) or if model instance has never been saved before, i.e. no pk set, because there is a chance that field was initialized through model's `...
entailment
def get_status_key(self, instance): """Generates a key used to set a status on a field""" key_id = "inst_%s" % id(instance) if instance.pk is None else instance.pk return "%s.%s-%s-%s" % (instance._meta.app_label, get_model_name(instance), ...
Generates a key used to set a status on a field
entailment
def get_status(self, instance): """Retrives a status of a field from cache. Fields in state 'error' and 'complete' will not retain the status after the call. """ status_key, status = self._get_status(instance) if status['state'] in ['complete', 'error']: cache.delete...
Retrives a status of a field from cache. Fields in state 'error' and 'complete' will not retain the status after the call.
entailment
def set_status(self, instance, status): """Sets the field status for up to 5 minutes.""" status_key = self.get_status_key(instance) cache.set(status_key, status, timeout=300)
Sets the field status for up to 5 minutes.
entailment
def get_mode(self, old_mode=None): """Returns output mode. If `mode` not set it will try to guess best mode, or next best mode comparing to old mode """ if self.mode is not None: return self.mode assert self.can_write, "This format does not have a supported output mo...
Returns output mode. If `mode` not set it will try to guess best mode, or next best mode comparing to old mode
entailment
def token_at_cursor(code, pos=0): """ Find the token present at the passed position in the code buffer :return (tuple): a pair (token, start_position) """ l = len(code) end = start = pos # Go forwards while we get alphanumeric chars while end < l and code[end].isalpha(): end += ...
Find the token present at the passed position in the code buffer :return (tuple): a pair (token, start_position)
entailment
def _send(self, data, msg_type='ok', silent=False): """ Send a response to the frontend and return an execute message @param data: response to send @param msg_type (str): message type: 'ok', 'raw', 'error', 'multi' @param silent (bool): suppress output @return (dict):...
Send a response to the frontend and return an execute message @param data: response to send @param msg_type (str): message type: 'ok', 'raw', 'error', 'multi' @param silent (bool): suppress output @return (dict): the return value for the kernel
entailment
def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False): """ Method called to execute a cell """ self._klog.info("[%.30s] [%d] [%s]", code, silent, user_expressions) # Split lines and remove empty lines & comments ...
Method called to execute a cell
entailment
def do_inspect(self, code, cursor_pos, detail_level=0): """ Method called on help requests """ self._klog.info("{%s}", code[cursor_pos:cursor_pos+10]) # Find the token for which help is requested token, start = token_at_cursor(code, cursor_pos) self._klog.debug("...
Method called on help requests
entailment
def do_complete(self, code, cursor_pos): """ Method called on autocompletion requests """ self._klog.info("{%s}", code[cursor_pos:cursor_pos+10]) token, start = token_at_cursor(code, cursor_pos) tkn_low = token.lower() if is_magic(token, start, code): ...
Method called on autocompletion requests
entailment
def run(self): '''The body of the tread: read lines and put them on the queue.''' for line in iter(self._fd.readline, ''): self._queue.put(line)
The body of the tread: read lines and put them on the queue.
entailment
def escape( x, lb=False ): """ Ensure a string does not contain HTML-reserved characters (including double quotes) Optionally also insert a linebreak if the string is too long """ # Insert a linebreak? Roughly around the middle of the string, if lb: l = len(x) if l >= 10: ...
Ensure a string does not contain HTML-reserved characters (including double quotes) Optionally also insert a linebreak if the string is too long
entailment
def div( txt, *args, **kwargs ): """ Create & return an HTML <div> element by wrapping the passed text buffer. @param txt (basestring): the text buffer to use @param *args (list): if present, \c txt is considered a Python format string, and the arguments are formatted into it @param kw...
Create & return an HTML <div> element by wrapping the passed text buffer. @param txt (basestring): the text buffer to use @param *args (list): if present, \c txt is considered a Python format string, and the arguments are formatted into it @param kwargs (dict): the \c css field can contain the...
entailment
def data_msglist( msglist ): """ Return a Jupyter display_data message, in both HTML & text formats, by joining together all passed messages. @param msglist (iterable): an iterable containing a list of tuples (message, css_style) Each message is either a text string, or a list. In...
Return a Jupyter display_data message, in both HTML & text formats, by joining together all passed messages. @param msglist (iterable): an iterable containing a list of tuples (message, css_style) Each message is either a text string, or a list. In the latter case it is assumed to be ...
entailment
def data_msg( msg, mtype=None ): """ Return a Jupyter display_data message, in both HTML & text formats, by formatting a given single message. The passed message may be: * An exception (including a KrnlException): will generate an error message * A list of messages (with \c mtype equal to \c mu...
Return a Jupyter display_data message, in both HTML & text formats, by formatting a given single message. The passed message may be: * An exception (including a KrnlException): will generate an error message * A list of messages (with \c mtype equal to \c multi) * A single message @param m...
entailment
def copyresource( resource, filename, destdir ): """ Copy a resource file to a destination """ data = pkgutil.get_data(resource, os.path.join('resources',filename) ) #log.info( "Installing %s", os.path.join(destdir,filename) ) with open( os.path.join(destdir,filename), 'wb' ) as fp: fp.w...
Copy a resource file to a destination
entailment
def install_kernel_resources( destdir, resource=PKGNAME, files=None ): """ Copy the resource files to the kernelspec folder. """ if files is None: files = ['logo-64x64.png', 'logo-32x32.png'] for filename in files: try: copyresource( resource, filename, destdir ) ...
Copy the resource files to the kernelspec folder.
entailment
def install_custom_css( destdir, cssfile, resource=PKGNAME ): """ Add the kernel CSS to custom.css """ ensure_dir_exists( destdir ) custom = os.path.join( destdir, 'custom.css' ) prefix = css_frame_prefix(resource) # Check if custom.css already includes it. If so, let's remove it first ...
Add the kernel CSS to custom.css
entailment
def remove_custom_css(destdir, resource=PKGNAME ): """ Remove the kernel CSS from custom.css """ # Remove the inclusion in the main CSS if not os.path.isdir( destdir ): return False custom = os.path.join( destdir, 'custom.css' ) copy = True found = False prefix = css_frame_p...
Remove the kernel CSS from custom.css
entailment
def html_elem(e, ct, withtype=False): """ Format a result element as an HTML table cell. @param e (list): a pair \c (value,type) @param ct (str): cell type (th or td) @param withtype (bool): add an additional cell with the element type """ # Header cell if ct == 'th': retur...
Format a result element as an HTML table cell. @param e (list): a pair \c (value,type) @param ct (str): cell type (th or td) @param withtype (bool): add an additional cell with the element type
entailment
def html_table(data, header=True, limit=None, withtype=False): """ Return a double iterable as an HTML table @param data (iterable): the data to format @param header (bool): if the first row is a header row @param limit (int): maximum number of rows to render (excluding header) @param wi...
Return a double iterable as an HTML table @param data (iterable): the data to format @param header (bool): if the first row is a header row @param limit (int): maximum number of rows to render (excluding header) @param withtype (bool): if columns are to have an alternating CSS class (eve...
entailment
def jtype(c): """ Return the a string with the data type of a value, for JSON data """ ct = c['type'] return ct if ct != 'literal' else '{}, {}'.format(ct, c.get('xml:lang'))
Return the a string with the data type of a value, for JSON data
entailment
def gtype(n): """ Return the a string with the data type of a value, for Graph data """ t = type(n).__name__ return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language)
Return the a string with the data type of a value, for Graph data
entailment
def lang_match_json(row, hdr, accepted_languages): '''Find if the JSON row contains acceptable language data''' if not accepted_languages: return True languages = set([row[c].get('xml:lang') for c in hdr if c in row and row[c]['type'] == 'literal']) return (not languages) or...
Find if the JSON row contains acceptable language data
entailment
def lang_match_rdf(triple, accepted_languages): '''Find if the RDF triple contains acceptable language data''' if not accepted_languages: return True languages = set([n.language for n in triple if isinstance(n, Literal)]) return (not languages) or (languages & accepted_languages)
Find if the RDF triple contains acceptable language data
entailment
def lang_match_xml(row, accepted_languages): '''Find if the XML row contains acceptable language data''' if not accepted_languages: return True column_languages = set() for elem in row: lang = elem[0].attrib.get(XML_LANG, None) if lang: column_languages.add(lang) ...
Find if the XML row contains acceptable language data
entailment
def json_iterator(hdr, rowlist, lang, add_vtype=False): """ Convert a JSON response into a double iterable, by rows and columns Optionally add element type, and filter triples by language (on literals) """ # Return the header row yield hdr if not add_vtype else ((h, 'type') for h in hdr) # N...
Convert a JSON response into a double iterable, by rows and columns Optionally add element type, and filter triples by language (on literals)
entailment
def rdf_iterator(graph, lang, add_vtype=False): """ Convert a Graph response into a double iterable, by triples and elements. Optionally add element type, and filter triples by language (on literals) """ # Return the header row hdr = ('subject', 'predicate', 'object') yield hdr if not add_vt...
Convert a Graph response into a double iterable, by triples and elements. Optionally add element type, and filter triples by language (on literals)
entailment
def render_json(result, cfg, **kwargs): """ Render to output a result in JSON format """ result = json.loads(result.decode('utf-8')) head = result['head'] if 'results' not in result: if 'boolean' in result: r = u'Result: {}'.format(result['boolean']) else: ...
Render to output a result in JSON format
entailment
def xml_row(row, lang): ''' Generator for an XML row ''' for elem in row: name = elem.get('name') child = elem[0] ftype = re.sub(r'\{[^}]+\}', '', child.tag) if ftype == 'literal': ftype = '{}, {}'.format(ftype, child.attrib.get(XML_LANG, 'none')) yiel...
Generator for an XML row
entailment
def xml_iterator(columns, rowlist, lang, add_vtype=False): """ Convert an XML response into a double iterable, by rows and columns Options are: filter triples by language (on literals), add element type """ # Return the header row yield columns if not add_vtype else ((h, 'type') for h in columns...
Convert an XML response into a double iterable, by rows and columns Options are: filter triples by language (on literals), add element type
entailment
def render_xml(result, cfg, **kwargs): """ Render to output a result in XML format """ # Raw mode if cfg.dis == 'raw': return {'data': {'text/plain': result.decode('utf-8')}, 'metadata': {}} # Table try: import xml.etree.cElementTree as ET except ImportErr...
Render to output a result in XML format
entailment
def render_graph(result, cfg, **kwargs): """ Render to output a result that can be parsed as an RDF graph """ # Mapping from MIME types to formats accepted by RDFlib rdflib_formats = {'text/rdf+n3': 'n3', 'text/turtle': 'turtle', 'application/x-turtle': 't...
Render to output a result that can be parsed as an RDF graph
entailment
def magic(self, line): """ Read and process magics @param line (str): the full line containing a magic @return (list): a tuple (output-message,css-class), where the output message can be a single string or a list (containing a Python format string and its argu...
Read and process magics @param line (str): the full line containing a magic @return (list): a tuple (output-message,css-class), where the output message can be a single string or a list (containing a Python format string and its arguments)
entailment
def query(self, query, num=0, silent=False): """ Launch an SPARQL query, process & convert results and return them """ if self.srv is None: raise KrnlException('no endpoint defined') # Add to the query all predefined SPARQL prefixes if self.cfg.pfx: ...
Launch an SPARQL query, process & convert results and return them
entailment
def set_logging( logfilename=None, level=None ): """ Set a logging configuration, with a rolling file appender. If passed a filename, use it as the logfile, else use a default name. The default logfile is \c sparqlkernel.log, placed in the directory given by (in that order) the \c LOGDIR environmen...
Set a logging configuration, with a rolling file appender. If passed a filename, use it as the logfile, else use a default name. The default logfile is \c sparqlkernel.log, placed in the directory given by (in that order) the \c LOGDIR environment variable, the logdir specified upon kernel installation...
entailment
def smartfields_get_field_status(self, field_name): """A way to find out a status of a filed.""" manager = self._smartfields_managers.get(field_name, None) if manager is not None: return manager.get_status(self) return {'state': 'ready'}
A way to find out a status of a filed.
entailment
def get_ext(self, format=None, **kwargs): """Returns new file extension based on a processor's `format` parameter. Overwrite if different extension should be set ex: `'.txt'` or `None` if this processor does not change file's extension. """ try: format = format or se...
Returns new file extension based on a processor's `format` parameter. Overwrite if different extension should be set ex: `'.txt'` or `None` if this processor does not change file's extension.
entailment
def get_output_file(self, in_file, instance, field, **kwargs): """Creates a temporary file. With regular `FileSystemStorage` it does not need to be deleted, instaed file is safely moved over. With other cloud based storage it is a good idea to set `delete=True`.""" return NamedTemporary...
Creates a temporary file. With regular `FileSystemStorage` it does not need to be deleted, instaed file is safely moved over. With other cloud based storage it is a good idea to set `delete=True`.
entailment
def label(x, gr, preferred_languages=None): """ @param x : graph entity @param gr (Graph): RDF graph @param preferred_languages (iterable) Return the best available label in the graph for the passed entity. If a set of preferred languages is given, try them in order. If none is found,...
@param x : graph entity @param gr (Graph): RDF graph @param preferred_languages (iterable) Return the best available label in the graph for the passed entity. If a set of preferred languages is given, try them in order. If none is found, an arbitrary language will be chosen
entailment
def rdf2dot( g, stream, opts={} ): """ Convert the RDF graph to DOT Write the dot output to the stream """ accept_lang = set( opts.get('lang',[]) ) do_literal = opts.get('literal') nodes = {} links = [] def node_id(x): if x not in nodes: nodes[x] = "node%d" % le...
Convert the RDF graph to DOT Write the dot output to the stream
entailment
def draw_graph( g, fmt='svg', prg='dot', options={} ): """ Draw an RDF graph as an image """ # Convert RDF to Graphviz buf = StringIO() rdf2dot( g, buf, options ) gv_options = options.get('graphviz',[]) if fmt == 'png': gv_options += [ '-Gdpi=220', '-Gsize=25,10!' ] meta...
Draw an RDF graph as an image
entailment
def get_SZ(self, psd, geometry): """ Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and phase (Z) matrices. """ if (self._S_table is None) or (self._Z_table is None): raise AttributeError( ...
Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and phase (Z) matrices.
entailment
def init_scatter_table(self, tm, angular_integration=False, verbose=False): """Initialize the scattering lookup tables. Initialize the scattering lookup tables for the different geometries. Before calling this, the following attributes must be set: num_points, m_func, axis_ra...
Initialize the scattering lookup tables. Initialize the scattering lookup tables for the different geometries. Before calling this, the following attributes must be set: num_points, m_func, axis_ratio_func, D_max, geometries and additionally, all the desired attributes of the...
entailment
def save_scatter_table(self, fn, description=""): """Save the scattering lookup tables. Save the state of the scattering lookup tables to a file. This can be loaded later with load_scatter_table. Other variables will not be saved, but this does not matter because the re...
Save the scattering lookup tables. Save the state of the scattering lookup tables to a file. This can be loaded later with load_scatter_table. Other variables will not be saved, but this does not matter because the results of the computations are based only on the contents ...
entailment
def load_scatter_table(self, fn): """Load the scattering lookup tables. Load the scattering lookup tables saved with save_scatter_table. Args: fn: The name of the scattering table file. """ data = pickle.load(file(fn)) if ("version" not ...
Load the scattering lookup tables. Load the scattering lookup tables saved with save_scatter_table. Args: fn: The name of the scattering table file.
entailment
def gaussian_pdf(std=10.0, mean=0.0): """Gaussian PDF for orientation averaging. Args: std: The standard deviation in degrees of the Gaussian PDF mean: The mean in degrees of the Gaussian PDF. This should be a number in the interval [0, 180) Returns: pdf(x), a function t...
Gaussian PDF for orientation averaging. Args: std: The standard deviation in degrees of the Gaussian PDF mean: The mean in degrees of the Gaussian PDF. This should be a number in the interval [0, 180) Returns: pdf(x), a function that returns the value of the spherical Jacobi...
entailment
def uniform_pdf(): """Uniform PDF for orientation averaging. Returns: pdf(x), a function that returns the value of the spherical Jacobian- normalized uniform PDF. It is normalized for the interval [0, 180]. """ norm_const = 1.0 def pdf(x): return norm_const * np.sin(np.pi/18...
Uniform PDF for orientation averaging. Returns: pdf(x), a function that returns the value of the spherical Jacobian- normalized uniform PDF. It is normalized for the interval [0, 180].
entailment
def orient_averaged_adaptive(tm): """Compute the T-matrix using variable orientation scatterers. This method uses a very slow adaptive routine and should mainly be used for reference purposes. Uses the set particle orientation PDF, ignoring the alpha and beta attributes. Args: tm: TMat...
Compute the T-matrix using variable orientation scatterers. This method uses a very slow adaptive routine and should mainly be used for reference purposes. Uses the set particle orientation PDF, ignoring the alpha and beta attributes. Args: tm: TMatrix (or descendant) instance Returns...
entailment
def orient_averaged_fixed(tm): """Compute the T-matrix using variable orientation scatterers. This method uses a fast Gaussian quadrature and is suitable for most use. Uses the set particle orientation PDF, ignoring the alpha and beta attributes. Args: tm: TMatrix (or descendant) insta...
Compute the T-matrix using variable orientation scatterers. This method uses a fast Gaussian quadrature and is suitable for most use. Uses the set particle orientation PDF, ignoring the alpha and beta attributes. Args: tm: TMatrix (or descendant) instance. Returns: The amplitu...
entailment
def set_geometry(self, geom): """A convenience function to set the geometry variables. Args: geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatterer class documentation for a description of these angles. """ (self.thet0, self...
A convenience function to set the geometry variables. Args: geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatterer class documentation for a description of these angles.
entailment
def get_geometry(self): """A convenience function to get the geometry variables. Returns: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatterer class documentation for a description of these angles. """ return (self.thet0, self.t...
A convenience function to get the geometry variables. Returns: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatterer class documentation for a description of these angles.
entailment
def _init_tmatrix(self): """Initialize the T-matrix. """ if self.radius_type == Scatterer.RADIUS_MAXIMUM: # Maximum radius is not directly supported in the original # so we convert it to equal volume radius radius_type = Scatterer.RADIUS_EQUAL_VOLUME ...
Initialize the T-matrix.
entailment
def _init_orient(self): """Retrieve the quadrature points and weights if needed. """ if self.orient == orientation.orient_averaged_fixed: (self.beta_p, self.beta_w) = quadrature.get_points_and_weights( self.or_pdf, 0, 180, self.n_beta) self._set_orient_signatu...
Retrieve the quadrature points and weights if needed.
entailment
def _set_scatter_signature(self): """Mark the amplitude and scattering matrices as up to date. """ self._scatter_signature = (self.thet0, self.thet, self.phi0, self.phi, self.alpha, self.beta, self.orient)
Mark the amplitude and scattering matrices as up to date.
entailment
def get_SZ_single(self, alpha=None, beta=None): """Get the S and Z matrices for a single orientation. """ if alpha == None: alpha = self.alpha if beta == None: beta = self.beta tm_outdated = self._tm_signature != (self.radius, self.radius_type, ...
Get the S and Z matrices for a single orientation.
entailment
def get_SZ_orient(self): """Get the S and Z matrices using the specified orientation averaging. """ tm_outdated = self._tm_signature != (self.radius, self.radius_type, self.wavelength, self.m, self.axis_ratio, self.shape, self.ddelt, self.ndgs) scatter_outdated...
Get the S and Z matrices using the specified orientation averaging.
entailment
def get_SZ(self): """Get the S and Z matrices using the current parameters. """ if self.psd_integrator is None: (self._S, self._Z) = self.get_SZ_orient() else: scatter_outdated = self._scatter_signature != (self.thet0, self.thet, self.phi0, self.p...
Get the S and Z matrices using the current parameters.
entailment
def get_points_and_weights(w_func=lambda x : np.ones(x.shape), left=-1.0, right=1.0, num_points=5, n=4096): """Quadratude points and weights for a weighting function. Points and weights for approximating the integral I = \int_left^right f(x) w(x) dx given the weighting function w(x) using the...
Quadratude points and weights for a weighting function. Points and weights for approximating the integral I = \int_left^right f(x) w(x) dx given the weighting function w(x) using the approximation I ~ w_i f(x_i) Args: w_func: The weighting function w(x). Must be a function that ta...
entailment
def sca_intensity(scatterer, h_pol=True): """Scattering intensity (phase function) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The differential scatter...
Scattering intensity (phase function) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The differential scattering cross section.
entailment
def ldr(scatterer, h_pol=True): """ Linear depolarizarion ratio (LDR) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), return LDR_h. If False, return LDR_v. Returns: The LDR. """ Z = scatterer.get_Z() if h_pol: r...
Linear depolarizarion ratio (LDR) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), return LDR_h. If False, return LDR_v. Returns: The LDR.
entailment
def sca_xsect(scatterer, h_pol=True): """Scattering cross section for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The scattering cross s...
Scattering cross section for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The scattering cross section.
entailment
def ext_xsect(scatterer, h_pol=True): """Extinction cross section for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The extinction cross s...
Extinction cross section for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The extinction cross section.
entailment
def ssa(scatterer, h_pol=True): """Single-scattering albedo for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The single-scattering albedo...
Single-scattering albedo for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The single-scattering albedo.
entailment
def asym(scatterer, h_pol=True): """Asymmetry parameter for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The asymmetry parameter. """...
Asymmetry parameter for the current setup, with polarization. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The asymmetry parameter.
entailment
def radar_xsect(scatterer, h_pol=True): """Radar cross section for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The radar cross section. """ Z = sca...
Radar cross section for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The radar cross section.
entailment
def refl(scatterer, h_pol=True): """Reflectivity (with number concentration N=1) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The reflectivity. NOTE: T...
Reflectivity (with number concentration N=1) for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The reflectivity. NOTE: To compute reflectivity in dBZ, give the ...
entailment
def delta_hv(scatterer): """ Delta_hv for the current setup. Args: scatterer: a Scatterer instance. Returns: Delta_hv [rad]. """ Z = scatterer.get_Z() return np.arctan2(Z[2,3] - Z[3,2], -Z[2,2] - Z[3,3])
Delta_hv for the current setup. Args: scatterer: a Scatterer instance. Returns: Delta_hv [rad].
entailment
def rho_hv(scatterer): """ Copolarized correlation (rho_hv) for the current setup. Args: scatterer: a Scatterer instance. Returns: rho_hv. """ Z = scatterer.get_Z() a = (Z[2,2] + Z[3,3])**2 + (Z[3,2] - Z[2,3])**2 b = (Z[0,0] - Z[0,1] - Z[1,0] + Z[1,1]) c = (Z[0,0] + ...
Copolarized correlation (rho_hv) for the current setup. Args: scatterer: a Scatterer instance. Returns: rho_hv.
entailment