docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
This method search for the zero-crossing of the watched parameter Args: begin (Orbit): end (Orbit) listener (Listener) Return Return
def _bisect(self, begin, end, listener): step = (end.date - begin.date) / 2 while abs(step) >= self._eps_bisect: date = begin.date + step if self.SPEAKER_MODE == "global": orb = self.propagate(date) else: orb = begin.propagat...
570,243
Method that check whether or not the listener is triggered Args: orb (Orbit): Return: bool: True if there is a zero-crossing for the parameter watched by the listener
def check(self, orb): return self.prev is not None and np.sign(self(orb)) != np.sign(self(self.prev))
570,244
Gives the result of the transformation without in-place modifications Args: orbit (Orbit): new_form (str or Form): Returns: Coord
def __call__(self, orbit, new_form): if isinstance(new_form, Form): new_form = new_form.name coord = orbit.copy() if new_form != orbit.form.name: for a, b in self.steps(new_form): coord = getattr(self, "_{}_to_{}".format(a.name.lower(), b.name....
570,267
Interpolate data at a given date Args: date (Date): method (str): Method of interpolation to use order (int): In case of ``LAGRANGE`` method is used Return: Orbit:
def interpolate(self, date, method=None, order=None): if not self.start <= date <= self.stop: raise ValueError("Date '%s' not in range" % date) prev_idx = 0 ephem = self # Binary search of the orbit step just before the desired date while True: ...
570,282
Read CCSDS from a string, and provide the beyond class corresponding; Orbit or list of Orbit if it's an OPM, Ephem if it's an OEM. Args: text (str): Return: Orbit or Ephem Raise: ValueError: when the text is not a recognizable CCSDS format
def loads(text): if text.startswith("CCSDS_OEM_VERS"): func = _read_oem elif text.startswith("CCSDS_OPM_VERS"): func = _read_opm else: raise ValueError("Unknown CCSDS type") return func(text)
570,286
Read of OPM string Args: string (str): Text containing the OPM Return: Orbit:
def _read_opm(string): maneuvers = [] data = {} comments = {} for i, line in enumerate(string.splitlines()): if not line: continue if line.startswith("COMMENT"): comments[i] = line.split("COMMENT")[-1].strip() continue key, _, value = l...
570,290
Create a covariance matrix Args: orb (Orbit): Covariance from which this is the covariance values: 2D matrix frame (str): Frame in which the covariance is expressed
def __new__(cls, orb, values, frame=PARENT_FRAME): if isinstance(values, cls): frame = values.frame values = values.base obj = np.ndarray.__new__(cls, (6, 6), buffer=np.array(values), dtype=float) obj._frame = frame obj.orb = orb.copy(form="cartesian") ...
570,295
Here we deviate from what has been done everywhere else. Instead of taking the formulas available in the Vallado, we take those described in the files tab5.2{a,b,d}.txt. The result should be equivalent, but they are the last iteration of the IAU2000A as of June 2016 Args: date (Date) Return: ...
def _xysxy2(date): planets = _planets(date) x_tab, y_tab, s_tab = _tab('X'), _tab('Y'), _tab('s') ttt = date.change_scale('TT').julian_century # Units: micro-arcsecond X = -16616.99 + 2004191742.88 * ttt - 427219.05 * ttt ** 2 - 198620.54 * ttt ** 3\ - 46.05 * ttt ** 4 + 5.98 * ttt *...
570,304
Get The X, Y and s coordinates Args: date (Date): Return: 3-tuple of float: Values of X, Y and s, in radians
def _xys(date): X, Y, s_xy2 = _xysxy2(date) # convert milli-arcsecond to arcsecond dX, dY = date.eop.dx / 1000., date.eop.dy / 1000. # Convert arcsecond to degrees then to radians X = np.radians((X + dX) / 3600.) Y = np.radians((Y + dY) / 3600.) s = np.radians(s_xy2 / 3600.) - (X * Y...
570,305
Initialize a :class:`~.Plugin` instance and connect to MongoDB. Args: *nodes (str): One or more URLs of MongoDB nodes to connect to as the persistence layer
def __init__(self, config=None): self.driver = get_database_instance(config) self.logger = logging.getLogger('Plugin') logging.basicConfig(level=logging.INFO)
570,307
Initialize the propagator Args: orbit (Orbit)
def orbit(self, orbit): self._orbit = orbit tle = Tle.from_orbit(orbit) lines = tle.text.splitlines() if len(lines) == 3: _, line1, line2 = lines else: line1, line2 = lines self.tle = twoline2rv(line1, line2, wgs72)
570,317
Propagate the initialized orbit Args: date (Date or datetime.timedelta) Return: Orbit
def propagate(self, date): if type(date) is timedelta: date = self.orbit.date + date # Convert the date to a tuple usable by the sgp4 library _date = [float(x) for x in "{:%Y %m %d %H %M %S.%f}".format(date).split()] p, v = self.tle.propagate(*_date) # Con...
570,318
Compute state of orbit at a given date, past or future Args: date (Date) Return: Orbit:
def propagate(self, date): i0, Ω0, e0, ω0, M0, n0 = self.tle n0 *= 60 # conversion to min⁻¹ if isinstance(date, Date): t0 = self.tle.date.datetime tdiff = (date.datetime - t0).total_seconds() / 60. elif isinstance(date, timedelta): tdiff = d...
570,322
Check the validity of a TLE Args: text (tuple of str) Raise: ValueError
def _check_validity(cls, text): if not text[0].lstrip().startswith('1 ') or not text[1].lstrip().startswith('2 '): raise ValueError("Line number check failed") for line in text: line = line.strip() if str(cls._checksum(line)) != line[-1]: ra...
570,326
Compute the checksum of a full line Args: line (str): Line to compute the checksum from Return: int: Checksum (modulo 10)
def _checksum(cls, line): tr_table = str.maketrans({c: None for c in ascii_uppercase + "+ ."}) no_letters = line[:68].translate(tr_table).replace("-", "1") return sum([int(l) for l in no_letters]) % 10
570,327
Convert an orbit to it's TLE representation Args: orbit (Orbit) norad_id (str or int): cospar_id (str): Return: str: TLE representation
def from_orbit(cls, orbit, name=None, norad_id=None, cospar_id=None): name = "0 %s\n" % name if name is not None else "" norad_id = norad_id if norad_id is not None else "99999" if cospar_id is not None: y, _, i = cospar_id.partition('-') cospar_id = y[2:] + i ...
570,330
Generator of TLEs from a string Args: text (str): A text containing many TLEs comments (str): If a line starts with this character, it is ignored error (str): How to handle errors while parsing the text. Could be 'raise', 'warn' or 'ignore'. Yields: ...
def from_string(cls, text, comments="#", error="warn"): cache = [] for line in text.splitlines(): # If the line is empty or begins with a comment mark, we skip it. if not line.strip() or line.startswith(comments): continue # The startswith ...
570,331
Change the frame of the orbit Args: new_frame (str) Return: numpy.ndarray
def transform(self, new_frame): steps = self.__class__.steps(new_frame) orbit = self.orbit for _from, _to in steps: from_obj = _from(self.date, orbit) direct = "_to_%s" % _to if hasattr(from_obj, direct): rotation, offset = getatt...
570,336
Compute the offset necessary in order to convert from one time-scale to another Args: mjd (float): new_scale (str): Name of the desired scale Return: float: offset to apply in seconds
def offset(self, mjd, new_scale, eop): delta = 0 for one, two in self.steps(new_scale): one = one.name.lower() two = two.name.lower() # find the operation oper = "_scale_{}_minus_{}".format(two, one) # find the reverse operation ...
570,346
Generator of a date range Args: start (Date): stop (Date or datetime.timedelta)! step (timedelta): Keyword Args: inclusive (bool): If ``False``, the stopping date is not included. This is the same behavior as the built-in :py:func:`range`....
def range(cls, start=None, stop=None, step=None, inclusive=False): def sign(x): return (-1, 1)[x >= 0] if not step: raise ValueError("Null step") # Convert stop from timedelta to Date object if isinstance(stop, timedelta): stop...
570,360
Provide the last and next leap-second events relative to a date Args: date (float): Date in MJD Return: tuple:
def get_last_next(self, date): past, future = (None, None), (None, None) for mjd, value in reversed(self.data): if mjd <= date: past = (mjd, value) break future = (mjd, value) return past, future
570,381
Retrieve the database Args: dbname: Specify the name of the database to retrieve. If set to `None`, take the name from the configuration (see :ref:`configuration <eop-dbname>`) Return: object
def db(cls, dbname=None): cls._load_entry_points() dbname = dbname or config.get('eop', 'dbname', fallback=cls.DEFAULT_DBNAME) if dbname not in cls._dbs.keys(): raise EopError("Unknown database '%s'" % dbname) if isclass(cls._dbs[dbname]): # Instancia...
570,385
Retrieve Earth Orientation Parameters and timescales differences for a given date Args: mjd: Date expressed as Mean Julian Date dbname: Name of the database to use Return: Eop: Interpolated data for this particuliar MJD
def get(cls, mjd: float, dbname: str = None) -> Eop: try: value = cls.db(dbname)[mjd] except (EopError, KeyError) as e: if isinstance(e, KeyError): msg = "Missing EOP data for mjd = '%s'" % e else: msg = str(e) if...
570,386
Get the sideral time at a defined date Args: date (Date): longitude (float): Longitude of the observer (in degrees) East positive/West negative. model (str): 'mean' or 'apparent' for GMST and GAST respectively Return: float: Sideral time in degrees GMST: Greenwi...
def _sideral(date, longitude=0., model='mean', eop_correction=True, terms=106): t = date.change_scale('UT1').julian_century # Compute GMST in seconds theta = 67310.54841 + (876600 * 3600 + 8640184.812866) * t + 0.093104 * t ** 2\ - 6.2e-6 * t ** 3 # Conversion from second (time) to degre...
570,397
Computation of the velocity increment in the reference frame of the orbit Args: orb (Orbit): Return: numpy.array: Velocity increment, length 3
def dv(self, orb): orb = orb.copy(form="cartesian") if self.frame == "QSW": mat = to_qsw(orb).T elif self.frame == "TNW": mat = to_tnw(orb).T else: mat = np.identity(3) # velocity increment in the same reference frame as the orbit ...
570,402
Propagate the orbit to a new date Args: date (Date) Return: Orbit
def propagate(self, date): if self.propagator.orbit is not self: self.propagator.orbit = self return self.propagator.propagate(date)
570,418
Generator giving the propagation of the orbit at different dates Args: start (Date) stop (Date or timedelta) step (timedelta) Yield: Orbit
def ephemeris(self, **kwargs): for orb in self.iter(inclusive=True, **kwargs): yield orb
570,420
Get the shortest way between two nodes of the graph Args: goal (str): Name of the targeted node Return: list of Node
def path(self, goal): if goal == self.name: return [self] if goal not in self.routes: raise ValueError("Unknown '{0}'".format(goal)) obj = self path = [obj] while True: obj = obj.routes[goal].direction path.append(obj) ...
570,435
Get the list of individual relations leading to the targeted node Args: goal (str): Name of the targeted node Return: list of tuple of Node
def steps(self, goal): path = self.path(goal) for i in range(len(path) - 1): yield path[i], path[i + 1]
570,436
Create a higlass viewer that displays the specified tilesets Parameters: ----------- Returns ------- Nothing
def view(tilesets): from .server import Server from .client import View curr_view = View() server = Server() server.start(tilesets) for ts in tilesets: if (ts.track_type is not None and ts.track_position is not None): curr_view.add_track(ts.track_type, ...
570,782
Syntax-highlights HTML-rendered Markdown. Plucks sections to highlight that conform the the GitHub fenced code info string as defined at https://github.github.com/gfm/#info-string. Args: html (str): The rendered HTML. Returns: str: The HTML with Pygments syntax highlighting applied to...
def _highlight(html): formatter = pygments.formatters.HtmlFormatter(nowrap=True) code_expr = re.compile( r'<pre><code class="language-(?P<lang>.+?)">(?P<code>.+?)' r'</code></pre>', re.DOTALL) def replacer(match): try: lang = match.group('lang') lang =...
571,082
Parse arguments Args: parser (argparse.ArgumentParser)
def add_arguments(parser): parser.description = 'Examples:\n' \ 'python -m etk regex_extractor pattern /tmp/date.txt\n' \ 'cat /tmp/date.txt | python -m etk regex_extractor pattern' parser.add_argument('pattern', nargs='?', type=str, default=sys.stdin) ...
571,663
Initialize the extractor, storing mailing list and message information Args: email_url: str mailing_list_name: str extractor_name: str Returns:
def __init__(self, email_url: str, mailing_list_name: str, extractor_name: str) -> None: Extractor.__init__(self, input_type=InputType.TEXT, category="build_in_extractor", name=extractor_name) self.email...
571,674
Extracts email message information if it uses the old Mailman format Args: content: BeautifulSoup Returns: List[str]
def old_format(self, content: BeautifulSoup) -> List[str]: b = content.find('body') sender, date, nxt, rep_to = None, None, None, None strongs = b.findAll('strong', recursive=False) for s in strongs: field = str(s).split(">")[1].split("<")[0] if...
571,675
Extracts email message information if it uses the new Mailman format Args: content: BeautifulSoup Returns: List[str]
def new_format(self, navbar: BeautifulSoup, content: BeautifulSoup) -> List[str]: sender = content.find(id='from').text.split('via')[0][6:].strip() date_str = content.find(id='date').text.split(': ')[1].strip() date = parsedate_to_datetime(date_str).isoformat()[:19] bo...
571,676
Extracts and structures email message from UTF8-encoded text Args: text: str Returns: Extraction
def extract(self, text: str) -> List[Extraction]: content = BeautifulSoup(text, 'html5lib') subject = content.find('h1').text.strip() recip = self.mailing_list_name navbar = content.find(id='navbar') if navbar == None: info = self.old_forma...
571,677
Factory method to wrap input JSON docs in an ETK Document object. Args: doc (object): a JSON object containing a document in CDR format. mime_type (str): if doc is a string, the mime_type tells what it is url (str): if the doc came from the web, specifies the URL for it ...
def create_document(self, doc: Dict, mime_type: str = None, url: str = "http://ex.com/123", doc_id=None, type_=None) -> Document: return Document(self, doc, mime_type, url, doc_id=doc_id).with_type(type_)
571,714
Parse a jsonpath Args: jsonpath: str Returns: a parsed json path
def parse_json_path(self, jsonpath): if jsonpath not in self.parsed: try: self.parsed[jsonpath] = self.parser(jsonpath) except Exception: self.log("Invalid Json Path: " + jsonpath, "error") raise InvalidJsonPathError("Invalid Json...
571,715
Processes a document and if it has child docs, embeds them in the parent document. Only works for 1 level of nesting. Kind of hack, will implement properly later Args: doc: input document to be run etk modules on Returns:
def process_and_frame(self, doc: Document): nested_docs = self.process_ems(doc) parent_kg = doc.cdr_document.get('knowledge_graph', None) if parent_kg: if nested_docs and len(nested_docs) > 0: for nested_doc in nested_docs: json_doc = nest...
571,716
Factory method to wrap input JSON docs in an ETK Document object. Args: doc (Document): process on this document Returns: a Document object and a KnowledgeGraph object
def process_ems(self, doc: Document) -> List[Document]: new_docs = list() for a_em in self.em_lst: if a_em.document_selector(doc): self.log(" processing with " + str(type(a_em)) + ". Process", "info", doc.doc_id, doc.url) fresh_docs = a_em.process_do...
571,717
A glossary is a text file, one entry per line. Args: file_path (str): path to a text file containing a glossary. read_json (bool): set True if the glossary is in json format Returns: List of the strings in the glossary.
def load_glossary(file_path: str, read_json=False) -> List[str]: if read_json: if file_path.endswith(".gz"): return json.load(gzip.open(file_path)) return json.load(open(file_path)) return open(file_path).read().splitlines()
571,718
A spacy rule file is a json file. Args: file_path (str): path to a text file containing a spacy rule sets. Returns: Dict as the representation of spacy rules
def load_spacy_rule(file_path: str) -> Dict: with open(file_path) as fp: return json.load(fp)
571,719
Load all extraction modules from the path Args: modules_path: str Returns:
def load_ems(self, modules_paths: List[str]): all_em_lst = [] if modules_paths: for modules_path in modules_paths: em_lst = [] try: for file_name in os.listdir(modules_path): if file_name.startswith("em_") a...
571,720
Return all classes with super class ExtractionModule Args: module: Returns: List of classes
def classes_in_module(module) -> List: md = module.__dict__ return [ md[c] for c in md if ( isinstance(md[c], type) and issubclass(md[c], ETKModule ) and md[c].__module__ == module.__name__) ...
571,721
Extract with the input text, confidence and fields filter to be used. Args: text (str): text input to be annotated confidence (float): the confidence of the annotation filter (List[str]): the fields that to be extracted Returns: Li...
def extract(self, text: str, confidence=0.5, filter=['Person', 'Place', 'Organisation']) -> List[Extraction]: filter = ','.join(filter) search_data = [('confidence', confidence), ('text', text), ('types', filter)] search_headers = {'Accept'...
571,724
Convert list to str as input for tokenizer Args: l (list): list for converting joiner (str): join the elements using this string to separate them. Returns: the value of the list as a string
def list2str(self, l: List, joiner: str) -> str: result = str() for item in l: if isinstance(item, list): result = result + self.list2str(item, joiner) + joiner elif isinstance(item, dict): result = result + self.dict2str(item, joiner) + j...
571,803
Convert dict to str as input for tokenizer Args: d (dict): dict for converting joiner (str): join the elements using this string to separate them. Returns: the value of the dict as a string
def dict2str(self, d: Dict, joiner: str) -> str: result = str() for key in d: result = result + str(key) + " : " if isinstance(d[key], list): result = result + self.list2str(d[key], joiner) + joiner elif isinstance(d[key], dict): ...
571,804
Parse arguments Args: parser (argparse.ArgumentParser)
def add_arguments(parser): parser.description = 'Triple re-ontologization' parser.add_argument('-i', '--input-file', type=argparse.FileType('r'), dest='input_file') parser.add_argument('--input-type', action='store', dest='input_type', default='nt') parser.add_argument('-o', '--output-file', type=a...
571,813
Parse arguments Args: parser (argparse.ArgumentParser)
def add_arguments(parser): parser.description = 'Examples:\n' \ 'python -m etk html_content_extractor /tmp/input.html\n' \ 'cat /tmp/input.html | python -m etk html_content_extractor' parser.add_argument('input_file', nargs='?', type=argparse.FileType('r'),...
571,822
Extract relative dates using spaCy rules Args: text: str - the text to extract the relative date strings from Returns: List of Extraction(s)
def _extract_relative_dates(self, text: str) -> List[Extraction]: if not text or not self._etk: return list() base = self._settings[RELATIVE_BASE] if self._settings[RELATIVE_BASE] else datetime.datetime.now() if not self._settings[RETURN_AS_TIMEZONE_AWARE]: base ...
571,840
Post check the extracted date string to filter out some false positives Args: date_info: dict - includes the extracted string, matching groups, patterns etc. Returns: bool - if the date extracted is valid
def _post_check(date_info: dict) -> bool: if date_info['pattern']: return True # TODO: consider more context when extract dates?? (e.g. for 'may') if date_info['value'] == 'may' or re.match(illegal, date_info['value'])\ or (re.match(possible_illegal, date_info['v...
571,841
Record a mapping about each fields and its type from config file Args: config: Dict
def __init__(self, config: Dict) -> None: self.fields_dict = dict() try: for field in config["fields"]: if config["fields"][field]["type"] == "kg_id": self.fields_dict[field] = FieldType.KG_ID elif config["fields"][field]["type"] ...
571,863
Return iso format of a date Args: d: Returns: str
def iso_date(d) -> str: if isinstance(d, datetime): return d.isoformat() elif isinstance(d, date): return datetime.combine(d, datetime.min.time()).isoformat() else: try: datetime.strptime(d, '%Y-%m-%dT%H:%M:%S') return ...
571,864
Return true if the value type matches or can be coerced to the defined type in schema, otherwise false. If field not defined, return none Args: field_name: str value: Returns: bool, value, where the value may have been coerced to the required type.
def is_valid(self, field_name, value) -> (bool, object): if self.has_field(field_name): if self.fields_dict[field_name] == FieldType.KG_ID: return True, value if self.fields_dict[field_name] == FieldType.NUMBER: if isinstance(value, numbers.Numb...
571,866
Boolean function for checking if v is a date Args: v: Returns: bool
def is_date(v) -> (bool, date): if isinstance(v, date): return True, v try: reg = r'^([0-9]{4})(?:-(0[1-9]|1[0-2])(?:-(0[1-9]|[1-2][0-9]|3[0-1])(?:T' \ r'([0-5][0-9])(?::([0-5][0-9])(?::([0-5][0-9]))?)?)?)?)?$' match = re.match(reg, v) ...
571,867
Boolean function for checking if v is a location format Args: v: Returns: bool
def is_location(v) -> (bool, str): def convert2float(value): try: float_num = float(value) return float_num except ValueError: return False if not isinstance(v, str): return False, v split_lst = v.spli...
571,868
Wrapper object for CDR documents. Args: etk (ETK): embed the etk object so that docs have access to global info. cdr_document (JSON): the raw CDR document received in ETK. Returns: the wrapped CDR document
def __init__(self, etk, cdr_document: Dict, mime_type, url, doc_id=None) -> None: Segment.__init__(self, json_path="$", _value=cdr_document, _document=self) self.etk = etk self.cdr_document = cdr_document self.mime_type = mime_type self.url = url if doc_id: ...
571,870
Dereferences the json_path inside the document and returns the selected elements. This method should compile and cache the compiled json_path in case the same path is reused by multiple extractors. Args: jsonpath (str): a valid JSON path. Returns: A list of Segments object ...
def select_segments(self, jsonpath: str) -> List[Segment]: path = self.etk.parse_json_path(jsonpath) matches = path.find(self.cdr_document) segments = list() for a_match in matches: this_segment = Segment(str(a_match.full_path), a_match.value, self) segm...
571,871
Invoke the extractor on the given extractable, accumulating all the extractions in a list. Args: extractor (Extractor): extractable (extractable): tokenizer: user can pass custom tokenizer if extractor wants token joiner: user can pass joiner if extractor wants t...
def extract(self, extractor: Extractor, extractable: Extractable = None, tokenizer: Tokenizer = None, joiner: str = " ", **options) -> List[Extraction]: if not extractable: extractable = self if not tokenizer: tokenizer = self.etk.default_tokenizer ...
571,872
Each event has two actors. The relationship of the event to the actors depends on the cameo code and is defined by the mapping. Args: doc: the document containing the evence event: one of "event1", "event2", or "event3" cameo_code: Returns: the documents crea...
def add_actors(self, doc:Document, event: str, cameo_code: int) -> List[Document]: # Actor1 actor1_cdr = { "ActorName": doc.cdr_document[self.attribute("Actor1Name")], "ActorCountryCode": doc.cdr_document[self.attribute("Actor1CountryCode")], "ActorKnownGroup...
571,883
Return a list of all dates from 11/12/2015 to the present. Args: boo: if true, list contains Numbers (20151230); if false, list contains Strings ("2015-12-30") Returns: list of either Numbers or Strings
def all_days(boo): earliest = datetime.strptime(('2015-11-12').replace('-', ' '), '%Y %m %d') latest = datetime.strptime(datetime.today().date().isoformat().replace('-', ' '), '%Y %m %d') num_days = (latest - earliest).days + 1 all_days = [latest - timedelta(days=x) for x in range(num_days)] all_days.rever...
571,889
Clean the numerical date value in order to present it. Args: boo: numerical date (20160205) Returns: Stringified version of the input date ("2016-02-05")
def date_clean(date, dashboard_style=False): if dashboard_style: dt = str(date) out = dt[4:6] + '/' + dt[6:] + '/' + dt[:4] else: dt = str(date) out = dt[:4] + '-' + dt[4:6] + '-' + dt[6:] return out
571,893
Return list of dates within a specified range, inclusive. Args: start: earliest date to include, String ("2015-11-25") end: latest date to include, String ("2015-12-01") boo: if true, output list contains Numbers (20151230); if false, list contains Strings ("2015-12-30") Returns: list of either Num...
def date_range(start, end, boo): earliest = datetime.strptime(start.replace('-', ' '), '%Y %m %d') latest = datetime.strptime(end.replace('-', ' '), '%Y %m %d') num_days = (latest - earliest).days + 1 all_days = [latest - timedelta(days=x) for x in range(num_days)] all_days.reverse() output = [] if b...
571,895
Return today's date as either a String or a Number, as specified by the User. Args: boo: if true, function returns Number (20151230); if false, returns String ("2015-12-30") Returns: either a Number or a string, dependent upon the user's input
def today(boo): tod = datetime.strptime(datetime.today().date().isoformat().replace('-', ' '), '%Y %m %d') if boo: return int(str(tod).replace('-', '')[:8]) else: return str(tod)[:10]
571,915
Extracts information from a string(TEXT) with the GlossaryExtractor instance Args: token (List[Token]): list of spaCy token to be processed. Returns: List[Extraction]: the list of extraction or the empty list if there are no matches.
def extract(self, tokens: List[Token]) -> List[Extraction]: results = list() if len(tokens) > 0: if self._case_sensitive: new_tokens = [x.orth_ if isinstance(x, Token) else x for x in tokens] else: new_tokens = [x.lower_ if isinstance(x, ...
571,920
Initialize the extractor, storing the rule information and construct spacy rules Args: nlp rules (Dict): spacy rules extractor_name: str Returns:
def __init__(self, nlp, rules: Dict, extractor_name: str) -> None: Extractor.__init__(self, input_type=InputType.TEXT, category="spacy_rule_extractor", name=extractor_nam...
571,929
Extract from text Args: text (str): input str to be extracted. Returns: List[Extraction]: the list of extraction or the empty list if there are no matches.
def extract(self, text: str) -> List[Extraction]: doc = self._tokenizer.tokenize_to_spacy_doc(text) self._load_matcher() matches = [x for x in self._matcher(doc) if x[1] != x[2]] pos_filtered_matches = [] neg_filtered_matches = [] for idx, start, end in matches...
571,930
Filter the match result according to prefix, suffix, min, max ... Args: span: span relations: Dict patterns: List of pattern Returns: bool
def _filter_match(self, span: span, relations: Dict, patterns: List) -> bool: for pattern_id, a_pattern in enumerate(patterns): token_range = relations[pattern_id] if token_range: tokens = [x for x in span[token_range[0]:token_range[1]]] if a_pat...
571,932
Get the longest match for overlap Args: value_lst: List Returns: List
def _get_longest(value_lst: List) -> List: value_lst.sort() result = [] pivot = value_lst[0] start, end = pivot[0], pivot[1] pivot_e = end pivot_s = start for idx, (s, e, v, rule_id, _) in enumerate(value_lst): if s == pivot_s and pivot_e < e...
571,933
Reject some positive matches according to negative matches Args: pos_lst: List neg_lst: List Returns: List
def _reject_neg(pos_lst: List, neg_lst: List) -> List: pos_lst.sort() neg_lst.sort() result = [] pivot_pos = pos_lst[0] pivot_neg = neg_lst[0] while pos_lst: if pivot_pos[1] <= pivot_neg[0]: result.append(pivot_pos) po...
571,934
Prefix and Suffix filter Args: t: List, list of tokens prefix: str suffix: str Returns: bool
def _pre_suf_fix_filter(t: List, prefix: str, suffix: str) -> bool: if prefix: for a_token in t: if a_token._.n_prefix(len(prefix)) != prefix: return False if suffix: for a_token in t: if a_token._.n_suffix(len(suffix)...
571,935
Min and Max filter Args: t: List, list of tokens min_v: str max_v: str Returns: bool
def _min_max_filter(t: List, min_v: str, max_v: str) -> bool: def tofloat(value): try: float(value) return float(value) except ValueError: return False for a_token in t: if not tofloat(a_token.text): ...
571,936
Shape filter Args: t: List, list of tokens shapes: List Returns: bool
def _full_shape_filter(t: List, shapes: List) -> bool: if shapes: for a_token in t: if a_token._.full_shape not in shapes: return False return True
571,937
Form an output value according to user input of output_format Args: span_doc: span format: str relations: Dict patterns: List Returns: str
def _form_output(span_doc: span, output_format: str, relations: Dict, patterns: List) -> str: format_value = [] output_inf = [a_pattern.in_output for a_pattern in patterns] for i in range(len(output_inf)): token_range = relations[i] if token_range and output_inf...
571,938
Use a mapping to store the information about rule_id for each matches, create the mapping key here Args: rule_id: str spacy_rule_id:int Returns: int
def _construct_key(self, rule_id: str, spacy_rule_id:int) -> int: hash_key = (rule_id, spacy_rule_id) hash_v = hash(hash_key) + sys.maxsize + 1 self._hash_map[hash_v] = hash_key return hash_v
571,939
Get the relations between the each pattern in the spacy rule and the matches Args: span_doc: doc r: List Returns: Dict
def _find_relation(self, span_doc: doc, r: List) -> Dict: rule = r[1][0] span_pivot = 0 relation = {} for e_id, element in enumerate(rule): if not span_doc[span_pivot:]: for extra_id, _, in enumerate(rule[e_id:]): relation[e_id+ex...
571,940
Initialize a pattern, construct spacy token for matching according to type Args: d: Dict nlp Returns:
def __init__(self, d: Dict, nlp) -> None: self.type = d["type"] self.in_output = tf_transfer(d["is_in_output"]) self.max = d["maximum"] self.min = d["minimum"] self.prefix = d["prefix"] self.suffix = d["suffix"] self.full_shape = d.get("shapes") ...
571,941
Construct a word token Args: d: Dict nlp Returns: List[Dict]
def _construct_word_token(self, d: Dict, nlp) -> List[Dict]: result = [] if len(d["token"]) == 1: if tf_transfer(d["match_all_forms"]): this_token = {attrs.LEMMA: nlp(d["token"][0])[0].lemma_} else: this_token = {attrs.LOWER: d["token"][0...
571,942
Construct a shape token Args: d: Dict Returns: List[Dict]
def _construct_shape_token(self, d: Dict) -> List[Dict]: result = [] if not d["shapes"]: this_token = {attrs.IS_ASCII: True} result.append(this_token) else: for shape in d["shapes"]: this_shape = self._generate_shape(shape) ...
571,943
Construct a shape token Args: d: Dict nlp Returns: List[Dict]
def _construct_number_token(self, d: Dict, nlp) -> List[Dict]: result = [] if not d["numbers"]: this_token = {attrs.LIKE_NUM: True} result.append(this_token) if d["length"]: result = self._add_length_constrain(result, d["length"]) eli...
571,944
Construct a shape token Args: d: Dict nlp Returns: List[Dict]
def _construct_punctuation_token(self, d: Dict, nlp) -> List[Dict]: result = [] if not d["token"]: this_token = {attrs.IS_PUNCT: True} elif len(d["token"]) == 1: this_token = {attrs.ORTH: d["token"][0]} else: global FLAG_ID punct_...
571,945
Construct a shape token Args: d: Dict Returns: List[Dict]
def _construct_linebreak_token(self, d: Dict) -> List[Dict]: result = [] num_break = int(d["length"][0]) if d["length"] else 1 if num_break: s = '' for i in range(num_break): s += '\n' this_token = {attrs.LOWER: s} result....
571,946
Add common constrain for every token type, like "is_required" Args: token_lst: List[Dict] d: Dict Returns: List[Dict]
def _add_common_constrain(token_lst: List[Dict], d: Dict) -> List[Dict]: result = [] for a_token in token_lst: if not tf_transfer(d["is_required"]): a_token["OP"] = "?" result.append(a_token) return result
571,947
Add length constrain for some token type, create cross production Args: token_lst: List[Dict] lengths: List Returns: List[Dict]
def _add_length_constrain(token_lst: List[Dict], lengths: List) -> List[Dict]: result = [] for a_token in token_lst: for length in lengths: if type(length) == str and length and length.isdigit(): a_token[attrs.LENGTH] = int(length) ...
571,948
Add pos tag constrain for some token type, create cross production Args: token_lst: List[Dict] pos_tags: List Returns: List[Dict]
def _add_pos_constrain(token_lst: List[Dict], pos_tags: List) -> List[Dict]: result = [] for a_token in token_lst: for pos in pos_tags: a_token[attrs.POS] = POS_MAP[pos] result.append(copy.deepcopy(a_token)) return result
571,949
Add capitalization constrain for some token type, create cross production Args: token_lst: List[Dict] capi_lst: List word_lst: List Returns: List[Dict]
def _add_capitalization_constrain(token_lst: List[Dict], capi_lst: List, word_lst: List) -> List[Dict]: result = [] for a_token in token_lst: if "exact" in capi_lst and word_lst != []: for word in word_lst: token = copy.deepcopy(a_token) ...
571,950
Recreate shape from a token input by user Args: word: str Returns: str
def _generate_shape(word: str) -> str: def counting_stars(w) -> List[int]: count = [1] for i in range(1, len(w)): if w[i - 1] == w[i]: count[-1] += 1 else: count.append(1) return count ...
571,951
Storing information for each Rule, create list of Pattern for a rule Args: d: Dict nlp Returns:
def __init__(self, d: Dict, nlp) -> None: self.dependencies = d["dependencies"] if "dependencies" in d else [] self.description = d["description"] if "description" in d else "" self.active = tf_transfer(d["is_active"]) self.identifier = d["identifier"] self.output_forma...
571,952
Make the document JSON serializable. This is a poor man's implementation that handles dates and nothing else. This method modifies the given document in place. Args: doc: A Python Dictionary, typically a CDR object. Returns: None
def make_json_serializable(doc: Dict): for k, v in doc.items(): if isinstance(v, datetime.date): doc[k] = v.strftime("%Y-%m-%d") elif isinstance(v, datetime.datetime): doc[k] = v.isoformat()
571,966
Docs with identical contents get the same ID. Args: doc: Returns: a string with the hash of the given document.
def create_doc_id_from_json(doc) -> str: return hashlib.sha256(json.dumps(doc, sort_keys=True).encode('utf-8')).hexdigest()
571,967
Look up the event tupe of an event Args: event: one of "event1", "event2" or "event3" cameo_code: one of the cameo codes Returns: a list of the event types or None if the event is not relevant.
def event_type(self, event, cameo_code) -> List[str]: key = self.event_name[event] entry = self.mapping.get(cameo_code) result = None if entry: result = entry[key] if result is None or result == "": return None elif not isinsta...
571,975
Determine the property to use for modeling an actor Args: event: one of "event1", "event2" or "event3" cameo_code: one of the cameo codes actor_regex: one of the regexes above Returns:
def _actor_property(self, event, cameo_code, actor_regex): if cameo_code not in self.mapping: return None arguments = self.mapping[cameo_code][event + "-arguments"] if not isinstance(arguments, list): arguments = [arguments] result = list() for ...
571,976
Test whether there is an "event2" or "event3" entry for the given cameo code Args: event: cameo_code: Returns:
def has_event(self, event, cameo_code): if self.has_cameo_code(cameo_code): entry = self.mapping.get(cameo_code) if entry: return entry[self.event_name[event]] return False
571,978
is_legal_subject(c) = true if - c in included_domains(self) or - super_classes_closure(c) intersection included_domains(self) is not empty There is no need to check the included_domains(super_properties_closure(self)) because included_domains(super_properties_closure(self)) is subset of...
def is_legal_subject(self, c: OntologyClass) -> bool: domains = self.included_domains() return c and (not domains or c in domains or c.super_classes_closure() & domains)
571,992
is_legal_object(c) = true if - c in included_ranges(self) or - super_classes_closure(c) intersection included_ranges(self) is not empty Args: c: Returns:
def is_legal_object(self, c: OntologyClass) -> bool: ranges = self.included_ranges() return not ranges or c in ranges or c.super_classes_closure() & ranges
571,994
Do data_type validation according to the rules of the XML xsd schema. Args: data_type: Returns:
def is_legal_object(self, data_type: str) -> bool: data_type = str(data_type) ranges = self.included_ranges() return not ranges or data_type in ranges or self.super_properties() and \ any(x.is_legal_object(data_type) for x in self.super_properties())
571,995
Splits text by sentences. Args: text (str): Input text to be extracted. Returns: List[Extraction]: the list of extraction or the empty list if there are no matches.
def extract(self, text: str) -> List[Extraction]: doc = self._parser(text) extractions = list() for sent in doc.sents: this_extraction = Extraction(value=sent.text, extractor_name=self.name, ...
572,038
Extracts text from an HTML page using a variety of strategies Args: html_text (str): html page in string strategy (enum[Strategy.ALL_TEXT, Strategy.MAIN_CONTENT_RELAXED, Strategy.MAIN_CONTENT_STRICT]): one of Strategy.ALL_TEXT, Strategy.MAIN_CONTENT_STRICT and Strategy.MAIN_...
def extract(self, html_text: str, strategy: Strategy=Strategy.ALL_TEXT) \ -> List[Extraction]: if html_text: if strategy == Strategy.ALL_TEXT: soup = BeautifulSoup(html_text, 'html.parser') texts = soup.findAll(text=True) visible_...
572,074
Complain if a field in not in the schema Args: field_name: Returns: True if the field is present.
def validate_field(self, field_name: str) -> bool: if field_name in {"@id", "@type"}: return True result = self.schema.has_field(field_name) if not result: # todo: how to comply with our error handling policies? raise UndefinedFieldError("'{}' should ...
572,138
Helper function to add values to a knowledge graph Args: field_name: a field in the knowledge graph, assumed correct value: any Python type Returns: True if the value is compliant with the field schema, False otherwise
def _add_value(self, field_name: str, value, provenance_path=None) -> bool: if not isinstance(value, list): value = [value] all_valid = True for x in value: valid = self._add_single_value(field_name, x, provenance_path=provenance_path) all_valid = al...
572,140