signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
@cached_property<EOL><INDENT>def jwt_veryfication_factory(self):<DEDENT>
|
return self.load_obj_or_import_string(<EOL>'<STR_LIT>'<EOL>)<EOL>
|
Load default JWT veryfication factory.
|
f3588:c0:m5
|
def __init__(self, app=None, **kwargs):
|
if app:<EOL><INDENT>self._state = self.init_app(app, **kwargs)<EOL><DEDENT>
|
Extension initialization.
:param app: An instance of :class:`flask.Flask`.
|
f3588:c1:m0
|
def init_app(self, app, entry_point_group='<STR_LIT>',<EOL>**kwargs):
|
self.init_config(app)<EOL>state = _OAuth2ServerState(app, entry_point_group=entry_point_group)<EOL>app.extensions['<STR_LIT>'] = state<EOL>return state<EOL>
|
Flask application initialization.
:param app: An instance of :class:`flask.Flask`.
:param entry_point_group: The entrypoint group name to load plugins.
(Default: ``'invenio_oauth2server.scopes'``)
|
f3588:c1:m1
|
def init_config(self, app):
|
app.config.setdefault(<EOL>'<STR_LIT>',<EOL>app.config.get('<STR_LIT>',<EOL>'<STR_LIT>'))<EOL>app.config.setdefault(<EOL>'<STR_LIT>',<EOL>app.config.get('<STR_LIT>',<EOL>'<STR_LIT>'))<EOL>app.config.setdefault(<EOL>'<STR_LIT>',<EOL>app.config.get('<STR_LIT>',<EOL>'<STR_LIT>'))<EOL>for k in dir(config):<EOL><INDENT>if k.startswith('<STR_LIT>') or k.startswith('<STR_LIT>'):<EOL><INDENT>app.config.setdefault(k, getattr(config, k))<EOL><DEDENT><DEDENT>
|
Initialize configuration.
:param app: An instance of :class:`flask.Flask`.
|
f3588:c1:m2
|
def __getattr__(self, name):
|
return getattr(self._state, name, None)<EOL>
|
Proxy to state object.
|
f3588:c1:m3
|
def __init__(self, app=None, **kwargs):
|
if app:<EOL><INDENT>self.init_app(app, **kwargs)<EOL><DEDENT>
|
Extension initialization.
:param app: An instance of :class:`flask.Flask`.
|
f3588:c2:m0
|
def init_app(self, app, **kwargs):
|
self.init_config(app)<EOL>allowed_urlencode_chars = app.config.get(<EOL>'<STR_LIT>')<EOL>if allowed_urlencode_chars:<EOL><INDENT>InvenioOAuth2ServerREST.monkeypatch_oauthlib_urlencode_chars(<EOL>allowed_urlencode_chars)<EOL><DEDENT>app.before_request(verify_oauth_token_and_set_current_user)<EOL>
|
Flask application initialization.
:param app: An instance of :class:`flask.Flask`.
|
f3588:c2:m1
|
def init_config(self, app):
|
app.config.setdefault(<EOL>'<STR_LIT>',<EOL>getattr(config, '<STR_LIT>'))<EOL>
|
Initialize configuration.
|
f3588:c2:m2
|
@staticmethod<EOL><INDENT>def monkeypatch_oauthlib_urlencode_chars(chars):<DEDENT>
|
modified_chars = set(chars)<EOL>always_safe = set(oauthlib_commmon.always_safe)<EOL>original_special_chars = oauthlib_commmon.urlencoded - always_safe<EOL>if modified_chars != original_special_chars:<EOL><INDENT>warnings.warn(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>RuntimeWarning<EOL>)<EOL>oauthlib_commmon.urlencoded = always_safe | modified_chars<EOL><DEDENT>
|
Monkeypatch OAuthlib set of "URL encoded"-safe characters.
.. note::
OAuthlib keeps a set of characters that it considers as valid
inside an URL-encoded query-string during parsing of requests. The
issue is that this set of characters wasn't designed to be
configurable since it should technically follow various RFC
specifications about URIs, like for example `RFC3986
<https://www.ietf.org/rfc/rfc3986.txt>`_. Many online services and
frameworks though have designed their APIs in ways that aim at
keeping things practical and readable to the API consumer, making
use of special characters to mark or seperate query-string
arguments. Such an example is the usage of embedded JSON strings
inside query-string arguments, which of course have to contain the
"colon" character (:) for key/value pair definitions.
Users of the OAuthlib library, in order to integrate with these
services and frameworks, end up either circumventing these "static"
restrictions of OAuthlib by pre-processing query-strings, or -in
search of a more permanent solution- directly make Pull Requests
to OAuthlib to include additional characters in the set, and
explain the logic behind their decision (one can witness these
efforts inside the git history of the source file that includes
this set of characters `here
<https://github.com/idan/oauthlib/commits/master/oauthlib/common.py>`_).
This kind of tactic leads easily to misconceptions about the
ability one has over the usage of specific features of services and
frameworks. In order to tackle this issue in Invenio-OAuth2Server,
we are monkey-patching this set of characters using a configuration
variable, so that usage of any special characters is a conscious
decision of the package user.
|
f3588:c2:m3
|
def scopes_multi_checkbox(field, **kwargs):
|
kwargs.setdefault('<STR_LIT:type>', '<STR_LIT>')<EOL>field_id = kwargs.pop('<STR_LIT:id>', field.id)<EOL>html = [u'<STR_LIT>']<EOL>for value, label, checked in field.iter_choices():<EOL><INDENT>choice_id = u'<STR_LIT>' % (field_id, value)<EOL>options = dict(<EOL>kwargs,<EOL>name=field.name,<EOL>value=value,<EOL>id=choice_id,<EOL>class_='<STR_LIT:U+0020>',<EOL>)<EOL>if checked:<EOL><INDENT>options['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>html.append(u'<STR_LIT>')<EOL>html.append(u'<STR_LIT>'.format(<EOL>choice_id<EOL>))<EOL>html.append(u'<STR_LIT>'.format(widgets.html_params(**options)))<EOL>html.append(u'<STR_LIT>'.format(<EOL>value, label.help_text<EOL>))<EOL>html.append(u'<STR_LIT>')<EOL><DEDENT>html.append(u'<STR_LIT>')<EOL>return HTMLString(u'<STR_LIT>'.join(html))<EOL>
|
Render multi checkbox widget.
|
f3590:m0
|
def process_formdata(self, valuelist):
|
if valuelist:<EOL><INDENT>self.data = '<STR_LIT:\n>'.join([<EOL>x.strip() for x in<EOL>filter(lambda x: x, '<STR_LIT:\n>'.join(valuelist).splitlines())<EOL>])<EOL><DEDENT>
|
Process form data.
|
f3590:c0:m0
|
def process_data(self, value):
|
self.data = '<STR_LIT:\n>'.join(value)<EOL>
|
Process data.
|
f3590:c0:m1
|
def __call__(self, form, field):
|
errors = []<EOL>for v in field.data.splitlines():<EOL><INDENT>try:<EOL><INDENT>validate_redirect_uri(v)<EOL><DEDENT>except InsecureTransportError:<EOL><INDENT>errors.append(v)<EOL><DEDENT>except InvalidRedirectURIError:<EOL><INDENT>errors.append(v)<EOL><DEDENT><DEDENT>if errors:<EOL><INDENT>raise validators.ValidationError(<EOL>_('<STR_LIT>', urls='<STR_LIT:U+002CU+0020>'.join(errors))<EOL>)<EOL><DEDENT>
|
Call function.
|
f3590:c1:m0
|
def upgrade():
|
op.drop_constraint('<STR_LIT>',<EOL>'<STR_LIT>', type_='<STR_LIT>')<EOL>op.create_foreign_key(op.f('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>', ['<STR_LIT>'],<EOL>['<STR_LIT:id>'], ondelete='<STR_LIT>')<EOL>op.create_index(op.f('<STR_LIT>'),<EOL>'<STR_LIT>', ['<STR_LIT>'], unique=False)<EOL>op.drop_constraint('<STR_LIT>',<EOL>'<STR_LIT>', type_='<STR_LIT>')<EOL>op.create_foreign_key(op.f('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>', ['<STR_LIT>'],<EOL>['<STR_LIT:id>'], ondelete='<STR_LIT>')<EOL>op.create_index(op.f('<STR_LIT>'),<EOL>'<STR_LIT>', ['<STR_LIT>'], unique=False)<EOL>op.drop_constraint('<STR_LIT>',<EOL>'<STR_LIT>', type_='<STR_LIT>')<EOL>op.create_foreign_key(<EOL>op.f('<STR_LIT>'),<EOL>'<STR_LIT>', '<STR_LIT>', ['<STR_LIT>'],<EOL>['<STR_LIT>'], ondelete='<STR_LIT>')<EOL>op.create_index(op.f('<STR_LIT>'),<EOL>'<STR_LIT>', ['<STR_LIT>'], unique=False)<EOL>
|
Upgrade database.
|
f3591:m0
|
def downgrade():
|
op.drop_constraint(op.f('<STR_LIT>'),<EOL>'<STR_LIT>', type_='<STR_LIT>')<EOL>op.drop_index(op.f('<STR_LIT>'),<EOL>table_name='<STR_LIT>')<EOL>op.create_foreign_key('<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', ['<STR_LIT>'],<EOL>['<STR_LIT:id>'])<EOL>op.drop_constraint(<EOL>op.f('<STR_LIT>'),<EOL>'<STR_LIT>', type_='<STR_LIT>')<EOL>op.drop_index(op.f('<STR_LIT>'),<EOL>table_name='<STR_LIT>')<EOL>op.create_foreign_key(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', ['<STR_LIT>'],<EOL>['<STR_LIT>'])<EOL>op.drop_constraint(op.f('<STR_LIT>'),<EOL>'<STR_LIT>', type_='<STR_LIT>')<EOL>op.drop_index(op.f('<STR_LIT>'),<EOL>table_name='<STR_LIT>')<EOL>op.create_foreign_key('<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', ['<STR_LIT>'],<EOL>['<STR_LIT:id>'])<EOL>
|
Downgrade database.
|
f3591:m1
|
def upgrade():
|
pass<EOL>
|
Upgrade database.
|
f3592:m0
|
def downgrade():
|
pass<EOL>
|
Downgrade database.
|
f3592:m1
|
def upgrade():
|
op.create_table(<EOL>'<STR_LIT>',<EOL>sa.Column('<STR_LIT:name>', sa.String(length=<NUM_LIT>), nullable=True),<EOL>sa.Column('<STR_LIT:description>', sa.Text(), nullable=True),<EOL>sa.Column(<EOL>'<STR_LIT>',<EOL>sqlalchemy_utils.types.url.URLType(),<EOL>nullable=True),<EOL>sa.Column('<STR_LIT>', sa.Integer(), nullable=True),<EOL>sa.Column('<STR_LIT>', sa.String(length=<NUM_LIT:255>), nullable=False),<EOL>sa.Column('<STR_LIT>', sa.String(length=<NUM_LIT:255>), nullable=False),<EOL>sa.Column(<EOL>'<STR_LIT>',<EOL>sa.Boolean(name='<STR_LIT>'),<EOL>nullable=True),<EOL>sa.Column(<EOL>'<STR_LIT>',<EOL>sa.Boolean(name='<STR_LIT>'),<EOL>nullable=True),<EOL>sa.Column('<STR_LIT>', sa.Text(), nullable=True),<EOL>sa.Column('<STR_LIT>', sa.Text(), nullable=True),<EOL>sa.ForeignKeyConstraint(['<STR_LIT>'], [u'<STR_LIT>'], ),<EOL>sa.PrimaryKeyConstraint('<STR_LIT>')<EOL>)<EOL>op.create_index(<EOL>op.f('<STR_LIT>'),<EOL>'<STR_LIT>',<EOL>['<STR_LIT>'],<EOL>unique=True<EOL>)<EOL>op.create_table(<EOL>'<STR_LIT>',<EOL>sa.Column('<STR_LIT:id>', sa.Integer(), nullable=False),<EOL>sa.Column('<STR_LIT>', sa.String(length=<NUM_LIT:255>), nullable=False),<EOL>sa.Column('<STR_LIT>', sa.Integer(), nullable=True),<EOL>sa.Column('<STR_LIT>', sa.String(length=<NUM_LIT:255>), nullable=True),<EOL>sa.Column(<EOL>'<STR_LIT>',<EOL>sqlalchemy_utils.EncryptedType(),<EOL>nullable=True),<EOL>sa.Column(<EOL>'<STR_LIT>',<EOL>sqlalchemy_utils.EncryptedType(),<EOL>nullable=True),<EOL>sa.Column('<STR_LIT>', sa.DateTime(), nullable=True),<EOL>sa.Column('<STR_LIT>', sa.Text(), nullable=True),<EOL>sa.Column(<EOL>'<STR_LIT>',<EOL>sa.Boolean(name='<STR_LIT>'),<EOL>nullable=True),<EOL>sa.Column(<EOL>'<STR_LIT>',<EOL>sa.Boolean(name='<STR_LIT>'),<EOL>nullable=True),<EOL>sa.ForeignKeyConstraint(<EOL>['<STR_LIT>'], [u'<STR_LIT>'], ),<EOL>sa.ForeignKeyConstraint(<EOL>['<STR_LIT>'], [u'<STR_LIT>'], ),<EOL>sa.PrimaryKeyConstraint('<STR_LIT:id>')<EOL>)<EOL>op.create_index(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>['<STR_LIT>'],<EOL>unique=True,<EOL>mysql_length=<NUM_LIT:255>)<EOL>op.create_index(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>['<STR_LIT>'],<EOL>unique=True,<EOL>mysql_length=<NUM_LIT:255>)<EOL>
|
Upgrade database.
|
f3593:m0
|
def downgrade():
|
op.drop_index(<EOL>'<STR_LIT>',<EOL>table_name='<STR_LIT>')<EOL>op.drop_index(<EOL>'<STR_LIT>',<EOL>table_name='<STR_LIT>')<EOL>op.drop_table('<STR_LIT>')<EOL>op.drop_index(<EOL>op.f('<STR_LIT>'),<EOL>table_name='<STR_LIT>')<EOL>op.drop_table('<STR_LIT>')<EOL>
|
Downgrade database.
|
f3593:m1
|
def rebuild_access_tokens(old_key):
|
current_app.logger.info('<STR_LIT>')<EOL>rebuild_encrypted_properties(old_key, Token,<EOL>['<STR_LIT>', '<STR_LIT>'])<EOL>
|
Rebuild the access_token field when the SECRET_KEY is changed.
Needed to fix the access tokens used in the REST API calls.
:param old_key: the old SECRET_KEY.
|
f3596:m0
|
def jwt_verify_token(headers):
|
<EOL>token = headers.get(<EOL>current_app.config['<STR_LIT>']<EOL>)<EOL>if token is None:<EOL><INDENT>raise JWTInvalidHeaderError<EOL><DEDENT>authentication_type =current_app.config['<STR_LIT>']<EOL>if authentication_type is not None:<EOL><INDENT>prefix, token = token.split()<EOL>if prefix != authentication_type:<EOL><INDENT>raise JWTInvalidHeaderError<EOL><DEDENT><DEDENT>try:<EOL><INDENT>decode = jwt_decode_token(token)<EOL>if current_user.get_id() != decode.get('<STR_LIT>'):<EOL><INDENT>raise JWTInvalidIssuer<EOL><DEDENT>return decode<EOL><DEDENT>except _JWTDecodeError as exc:<EOL><INDENT>raise_from(JWTDecodeError(), exc)<EOL><DEDENT>except _JWTExpiredToken as exc:<EOL><INDENT>raise_from(JWTExpiredToken(), exc)<EOL><DEDENT>
|
Verify the JWT token.
:param dict headers: The request headers.
:returns: The token data.
:rtype: dict
|
f3596:m1
|
def secret_key():
|
return current_app.config['<STR_LIT>'].encode('<STR_LIT:utf-8>')<EOL>
|
Return secret key as bytearray.
|
f3597:m0
|
def encrypt(self, value):
|
if value is not None:<EOL><INDENT>return super(NoneAesEngine, self).encrypt(value)<EOL><DEDENT>
|
Encrypt a value on the way in.
|
f3597:c0:m0
|
def decrypt(self, value):
|
if value is not None:<EOL><INDENT>return super(NoneAesEngine, self).decrypt(value)<EOL><DEDENT>
|
Decrypt value on the way out.
|
f3597:c0:m1
|
def __init__(self, user):
|
self._user = user<EOL>
|
Initialize proxy object with user instance.
|
f3597:c1:m0
|
def __getattr__(self, name):
|
return getattr(self._user, name)<EOL>
|
Pass any undefined attribute to the underlying object.
|
f3597:c1:m1
|
def __getstate__(self):
|
return self.id<EOL>
|
Return the id.
|
f3597:c1:m2
|
def __setstate__(self, state):
|
self._user = current_app.extensions['<STR_LIT>'].datastore.get_user(<EOL>state)<EOL>
|
Set user info.
|
f3597:c1:m3
|
@property<EOL><INDENT>def id(self):<DEDENT>
|
return self._user.get_id()<EOL>
|
Return user identifier.
|
f3597:c1:m4
|
def check_password(self, password):
|
return self.password == password<EOL>
|
Check user password.
|
f3597:c1:m5
|
@classmethod<EOL><INDENT>def get_current_user(cls):<DEDENT>
|
return cls(current_user._get_current_object())<EOL>
|
Return an instance of current user object.
|
f3597:c1:m6
|
def __init__(self, id_, help_text='<STR_LIT>', group='<STR_LIT>', internal=False):
|
self.id = id_<EOL>self.group = group<EOL>self.help_text = help_text<EOL>self.is_internal = internal<EOL>
|
Initialize scope values.
|
f3597:c2:m0
|
@property<EOL><INDENT>def allowed_grant_types(self):<DEDENT>
|
return current_app.config['<STR_LIT>']<EOL>
|
Return allowed grant types.
|
f3597:c3:m0
|
@property<EOL><INDENT>def allowed_response_types(self):<DEDENT>
|
return current_app.config['<STR_LIT>']<EOL>
|
Return allowed response types.
|
f3597:c3:m1
|
@property<EOL><INDENT>def client_type(self):<DEDENT>
|
if self.is_confidential:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>'<EOL>
|
Return client type.
|
f3597:c3:m2
|
@property<EOL><INDENT>def redirect_uris(self):<DEDENT>
|
if self._redirect_uris:<EOL><INDENT>return self._redirect_uris.splitlines()<EOL><DEDENT>return []<EOL>
|
Return redirect uris.
|
f3597:c3:m3
|
@redirect_uris.setter<EOL><INDENT>def redirect_uris(self, value):<DEDENT>
|
if isinstance(value, six.text_type):<EOL><INDENT>value = value.split("<STR_LIT:\n>")<EOL><DEDENT>value = [v.strip() for v in value]<EOL>for v in value:<EOL><INDENT>validate_redirect_uri(v)<EOL><DEDENT>self._redirect_uris = "<STR_LIT:\n>".join(value) or "<STR_LIT>"<EOL>
|
Validate and store redirect URIs for client.
|
f3597:c3:m4
|
@property<EOL><INDENT>def default_redirect_uri(self):<DEDENT>
|
try:<EOL><INDENT>return self.redirect_uris[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>
|
Return default redirect uri.
|
f3597:c3:m5
|
@property<EOL><INDENT>def default_scopes(self):<DEDENT>
|
if self._default_scopes:<EOL><INDENT>return self._default_scopes.split("<STR_LIT:U+0020>")<EOL><DEDENT>return []<EOL>
|
List of default scopes for client.
|
f3597:c3:m6
|
@default_scopes.setter<EOL><INDENT>def default_scopes(self, scopes):<DEDENT>
|
validate_scopes(scopes)<EOL>self._default_scopes = "<STR_LIT:U+0020>".join(set(scopes)) if scopes else "<STR_LIT>"<EOL>
|
Set default scopes for client.
|
f3597:c3:m7
|
def validate_scopes(self, scopes):
|
try:<EOL><INDENT>validate_scopes(scopes)<EOL>return True<EOL><DEDENT>except ScopeDoesNotExists:<EOL><INDENT>return False<EOL><DEDENT>
|
Validate if client is allowed to access scopes.
|
f3597:c3:m8
|
def gen_salt(self):
|
self.reset_client_id()<EOL>self.reset_client_secret()<EOL>
|
Generate salt.
|
f3597:c3:m9
|
def reset_client_id(self):
|
self.client_id = gen_salt(<EOL>current_app.config.get('<STR_LIT>')<EOL>)<EOL>
|
Reset client id.
|
f3597:c3:m10
|
def reset_client_secret(self):
|
self.client_secret = gen_salt(<EOL>current_app.config.get('<STR_LIT>')<EOL>)<EOL>
|
Reset client secret.
|
f3597:c3:m11
|
@property<EOL><INDENT>def get_users(self):<DEDENT>
|
no_users = Token.query.filter_by(<EOL>client_id=self.client_id,<EOL>is_personal=False,<EOL>is_internal=False<EOL>).count()<EOL>return no_users<EOL>
|
Get number of users.
|
f3597:c3:m12
|
@property<EOL><INDENT>def scopes(self):<DEDENT>
|
if self._scopes:<EOL><INDENT>return self._scopes.split()<EOL><DEDENT>return []<EOL>
|
Return all scopes.
:returns: A list of scopes.
|
f3597:c4:m0
|
@scopes.setter<EOL><INDENT>def scopes(self, scopes):<DEDENT>
|
validate_scopes(scopes)<EOL>self._scopes = "<STR_LIT:U+0020>".join(set(scopes)) if scopes else "<STR_LIT>"<EOL>
|
Set scopes.
:param scopes: The list of scopes.
|
f3597:c4:m1
|
def get_visible_scopes(self):
|
return [k for k, s in current_oauth2server.scope_choices()<EOL>if k in self.scopes]<EOL>
|
Get list of non-internal scopes for token.
:returns: A list of scopes.
|
f3597:c4:m2
|
@classmethod<EOL><INDENT>def create_personal(cls, name, user_id, scopes=None, is_internal=False):<DEDENT>
|
with db.session.begin_nested():<EOL><INDENT>scopes = "<STR_LIT:U+0020>".join(scopes) if scopes else "<STR_LIT>"<EOL>c = Client(<EOL>name=name,<EOL>user_id=user_id,<EOL>is_internal=True,<EOL>is_confidential=False,<EOL>_default_scopes=scopes<EOL>)<EOL>c.gen_salt()<EOL>t = Token(<EOL>client_id=c.client_id,<EOL>user_id=user_id,<EOL>access_token=gen_salt(<EOL>current_app.config.get(<EOL>'<STR_LIT>')<EOL>),<EOL>expires=None,<EOL>_scopes=scopes,<EOL>is_personal=True,<EOL>is_internal=is_internal,<EOL>)<EOL>db.session.add(c)<EOL>db.session.add(t)<EOL><DEDENT>return t<EOL>
|
Create a personal access token.
A token that is bound to a specific user and which doesn't expire, i.e.
similar to the concept of an API key.
:param name: Client name.
:param user_id: User ID.
:param scopes: The list of permitted scopes. (Default: ``None``)
:param is_internal: If ``True`` it's a internal access token.
(Default: ``False``)
:returns: A new access token.
|
f3597:c4:m3
|
def require_api_auth(allow_anonymous=False):
|
def wrapper(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>f_oauth_required = oauth2.require_oauth()(f)<EOL>@wraps(f)<EOL>def decorated(*args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not hasattr(current_user, '<STR_LIT>'):<EOL><INDENT>if not current_user.is_authenticated:<EOL><INDENT>if allow_anonymous:<EOL><INDENT>return f(*args, **kwargs)<EOL><DEDENT>abort(<NUM_LIT>)<EOL><DEDENT>if current_app.config['<STR_LIT>']:<EOL><INDENT>current_oauth2server.jwt_veryfication_factory(<EOL>request.headers)<EOL><DEDENT>return f(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>return f_oauth_required(*args, **kwargs)<EOL><DEDENT><DEDENT>return decorated<EOL><DEDENT>return wrapper<EOL>
|
Decorator to require API authentication using OAuth token.
:param allow_anonymous: Allow access without OAuth token
(default: ``False``).
|
f3598:m0
|
def require_oauth_scopes(*scopes):
|
required_scopes = set(scopes)<EOL>def wrapper(f):<EOL><INDENT>@wraps(f)<EOL>def decorated(*args, **kwargs):<EOL><INDENT>if hasattr(request, '<STR_LIT>') and request.oauth is not None:<EOL><INDENT>token_scopes = set(request.oauth.access_token.scopes)<EOL>if not required_scopes.issubset(token_scopes):<EOL><INDENT>abort(<NUM_LIT>)<EOL><DEDENT><DEDENT>return f(*args, **kwargs)<EOL><DEDENT>return decorated<EOL><DEDENT>return wrapper<EOL>
|
r"""Decorator to require a list of OAuth scopes.
Decorator must be preceded by a ``require_api_auth()`` decorator.
Note, API key authentication is bypassing this check.
:param \*scopes: List of scopes required.
|
f3598:m1
|
def error_handler(f):
|
@wraps(f)<EOL>def decorated(*args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>return f(*args, **kwargs)<EOL><DEDENT>except OAuth2Error as e:<EOL><INDENT>if hasattr(e, '<STR_LIT>'):<EOL><INDENT>return redirect(e.in_uri(e.redirect_uri))<EOL><DEDENT>else:<EOL><INDENT>return redirect(e.in_uri(oauth2.error_uri))<EOL><DEDENT><DEDENT><DEDENT>return decorated<EOL>
|
Handle uncaught OAuth errors.
|
f3599:m0
|
@blueprint.route('<STR_LIT>', methods=['<STR_LIT:GET>', '<STR_LIT:POST>'])<EOL>@register_breadcrumb(blueprint, '<STR_LIT:.>', _('<STR_LIT>'))<EOL>@login_required<EOL>@error_handler<EOL>@oauth2.authorize_handler<EOL>def authorize(*args, **kwargs):
|
if request.method == '<STR_LIT:GET>':<EOL><INDENT>client = Client.query.filter_by(<EOL>client_id=kwargs.get('<STR_LIT>')<EOL>).first()<EOL>if not client:<EOL><INDENT>abort(<NUM_LIT>)<EOL><DEDENT>scopes = current_oauth2server.scopes<EOL>ctx = dict(<EOL>client=client,<EOL>oauth_request=kwargs.get('<STR_LIT>'),<EOL>scopes=[scopes[x] for x in kwargs.get('<STR_LIT>', [])],<EOL>)<EOL>return render_template('<STR_LIT>', **ctx)<EOL><DEDENT>confirm = request.form.get('<STR_LIT>', '<STR_LIT>')<EOL>return confirm == '<STR_LIT:yes>'<EOL>
|
View for rendering authorization request.
|
f3599:m1
|
@blueprint.route('<STR_LIT>', methods=['<STR_LIT:POST>', ])<EOL>@oauth2.token_handler<EOL>def access_token():
|
client = Client.query.filter_by(<EOL>client_id=request.form.get('<STR_LIT>')<EOL>).first()<EOL>if not client:<EOL><INDENT>abort(<NUM_LIT>)<EOL><DEDENT>if not client.is_confidential and'<STR_LIT>' == request.form.get('<STR_LIT>'):<EOL><INDENT>error = InvalidClientError()<EOL>response = jsonify(dict(error.twotuples))<EOL>response.status_code = error.status_code<EOL>abort(response)<EOL><DEDENT>return None<EOL>
|
Token view handles exchange/refresh access tokens.
|
f3599:m2
|
@blueprint.route('<STR_LIT>')<EOL>def errors():
|
from oauthlib.oauth2.rfc6749.errors import raise_from_error<EOL>try:<EOL><INDENT>error = None<EOL>raise_from_error(request.values.get('<STR_LIT:error>'), params=dict())<EOL><DEDENT>except OAuth2Error as raised:<EOL><INDENT>error = raised<EOL><DEDENT>return render_template('<STR_LIT>', error=error)<EOL>
|
Error view in case of invalid oauth requests.
|
f3599:m3
|
@blueprint.route('<STR_LIT>', methods=['<STR_LIT:GET>', '<STR_LIT:POST>'])<EOL>@oauth2.require_oauth()<EOL>def ping():
|
return jsonify(dict(ping="<STR_LIT>"))<EOL>
|
Test to verify that you have been authenticated.
|
f3599:m4
|
@blueprint.route('<STR_LIT>')<EOL>@oauth2.require_oauth('<STR_LIT>')<EOL>def invalid():
|
if current_app.testing or current_app.debug:<EOL><INDENT>return jsonify(dict(ding="<STR_LIT>"))<EOL><DEDENT>else:<EOL><INDENT>abort(<NUM_LIT>)<EOL><DEDENT>
|
Test to verify that you have been authenticated.
|
f3599:m6
|
def client_getter():
|
def wrapper(f):<EOL><INDENT>@wraps(f)<EOL>def decorated(*args, **kwargs):<EOL><INDENT>if '<STR_LIT>' not in kwargs:<EOL><INDENT>abort(<NUM_LIT>)<EOL><DEDENT>client = Client.query.filter_by(<EOL>client_id=kwargs.pop('<STR_LIT>'),<EOL>user_id=current_user.get_id(),<EOL>).first()<EOL>if client is None:<EOL><INDENT>abort(<NUM_LIT>)<EOL><DEDENT>return f(client, *args, **kwargs)<EOL><DEDENT>return decorated<EOL><DEDENT>return wrapper<EOL>
|
Decorator to retrieve Client object and check user permission.
|
f3601:m0
|
def token_getter(is_personal=True, is_internal=False):
|
def wrapper(f):<EOL><INDENT>@wraps(f)<EOL>def decorated(*args, **kwargs):<EOL><INDENT>if '<STR_LIT>' not in kwargs:<EOL><INDENT>abort(<NUM_LIT>)<EOL><DEDENT>token = Token.query.filter_by(<EOL>id=kwargs.pop('<STR_LIT>'),<EOL>user_id=current_user.get_id(),<EOL>is_personal=is_personal,<EOL>is_internal=is_internal,<EOL>).first()<EOL>if token is None:<EOL><INDENT>abort(<NUM_LIT>)<EOL><DEDENT>return f(token, *args, **kwargs)<EOL><DEDENT>return decorated<EOL><DEDENT>return wrapper<EOL>
|
Decorator to retrieve Token object and check user permission.
:param is_personal: Search for a personal token. (Default: ``True``)
:param is_internal: Search for a internal token. (Default: ``False``)
|
f3601:m1
|
@blueprint.route("<STR_LIT:/>", methods=['<STR_LIT:GET>', '<STR_LIT:POST>'])<EOL>@login_required<EOL>@register_menu(<EOL>blueprint, '<STR_LIT>',<EOL>_('<STR_LIT>', icon='<STR_LIT>'),<EOL>order=<NUM_LIT:5>,<EOL>active_when=lambda: request.endpoint.startswith(<EOL>"<STR_LIT>")<EOL>)<EOL>@register_breadcrumb(<EOL>blueprint, '<STR_LIT>', _('<STR_LIT>')<EOL>)<EOL>def index():
|
clients = Client.query.filter_by(<EOL>user_id=current_user.get_id(),<EOL>is_internal=False,<EOL>).all()<EOL>tokens = Token.query.options(db.joinedload('<STR_LIT>')).filter(<EOL>Token.user_id == current_user.get_id(),<EOL>Token.is_personal == True, <EOL>Token.is_internal == False,<EOL>Client.is_internal == True,<EOL>).all()<EOL>authorized_apps = Token.query.options(db.joinedload('<STR_LIT>')).filter(<EOL>Token.user_id == current_user.get_id(),<EOL>Token.is_personal == False, <EOL>Token.is_internal == False,<EOL>Client.is_internal == False,<EOL>).all()<EOL>return render_template(<EOL>'<STR_LIT>',<EOL>clients=clients,<EOL>tokens=tokens,<EOL>authorized_apps=authorized_apps,<EOL>)<EOL>
|
List user tokens.
|
f3601:m2
|
@blueprint.route("<STR_LIT>", methods=['<STR_LIT:GET>', '<STR_LIT:POST>'])<EOL>@login_required<EOL>@register_breadcrumb(<EOL>blueprint, '<STR_LIT>', _('<STR_LIT>')<EOL>)<EOL>def client_new():
|
form = ClientForm(request.form)<EOL>if form.validate_on_submit():<EOL><INDENT>c = Client(user_id=current_user.get_id())<EOL>c.gen_salt()<EOL>form.populate_obj(c)<EOL>db.session.add(c)<EOL>db.session.commit()<EOL>return redirect(url_for('<STR_LIT>', client_id=c.client_id))<EOL><DEDENT>return render_template(<EOL>'<STR_LIT>',<EOL>form=form,<EOL>)<EOL>
|
Create new client.
|
f3601:m3
|
@blueprint.route("<STR_LIT>", methods=['<STR_LIT:GET>', '<STR_LIT:POST>'])<EOL>@login_required<EOL>@register_breadcrumb(<EOL>blueprint, '<STR_LIT>', _('<STR_LIT>')<EOL>)<EOL>@client_getter()<EOL>def client_view(client):
|
if request.method == '<STR_LIT:POST>' and '<STR_LIT>' in request.form:<EOL><INDENT>db.session.delete(client)<EOL>db.session.commit()<EOL>return redirect(url_for('<STR_LIT>'))<EOL><DEDENT>form = ClientForm(request.form, obj=client)<EOL>if form.validate_on_submit():<EOL><INDENT>form.populate_obj(client)<EOL>db.session.commit()<EOL><DEDENT>return render_template(<EOL>'<STR_LIT>',<EOL>client=client,<EOL>form=form,<EOL>)<EOL>
|
Show client's detail.
|
f3601:m4
|
@blueprint.route('<STR_LIT>', methods=['<STR_LIT:POST>'])<EOL>@login_required<EOL>@client_getter()<EOL>def client_reset(client):
|
if request.form.get('<STR_LIT>') == '<STR_LIT:yes>':<EOL><INDENT>client.reset_client_secret()<EOL>db.session.commit()<EOL><DEDENT>return redirect(url_for('<STR_LIT>', client_id=client.client_id))<EOL>
|
Reset client's secret.
|
f3601:m5
|
@blueprint.route("<STR_LIT>", methods=['<STR_LIT:GET>', '<STR_LIT:POST>'])<EOL>@login_required<EOL>@register_breadcrumb(<EOL>blueprint, '<STR_LIT>', _('<STR_LIT>')<EOL>)<EOL>def token_new():
|
form = TokenForm(request.form)<EOL>form.scopes.choices = current_oauth2server.scope_choices()<EOL>if form.validate_on_submit():<EOL><INDENT>t = Token.create_personal(<EOL>form.data['<STR_LIT:name>'], current_user.get_id(), scopes=form.scopes.data<EOL>)<EOL>db.session.commit()<EOL>session['<STR_LIT>'] = True<EOL>return redirect(url_for("<STR_LIT>", token_id=t.id))<EOL><DEDENT>if len(current_oauth2server.scope_choices()) == <NUM_LIT:0>:<EOL><INDENT>del(form.scopes)<EOL><DEDENT>return render_template(<EOL>"<STR_LIT>",<EOL>form=form,<EOL>)<EOL>
|
Create new token.
|
f3601:m6
|
@blueprint.route("<STR_LIT>", methods=['<STR_LIT:GET>', '<STR_LIT:POST>'])<EOL>@login_required<EOL>@register_breadcrumb(<EOL>blueprint, '<STR_LIT>', _('<STR_LIT>')<EOL>)<EOL>@token_getter()<EOL>def token_view(token):
|
if request.method == "<STR_LIT:POST>" and '<STR_LIT>' in request.form:<EOL><INDENT>db.session.delete(token)<EOL>db.session.commit()<EOL>return redirect(url_for('<STR_LIT>'))<EOL><DEDENT>show_token = session.pop('<STR_LIT>', False)<EOL>form = TokenForm(request.form, name=token.client.name, scopes=token.scopes)<EOL>form.scopes.choices = current_oauth2server.scope_choices()<EOL>if form.validate_on_submit():<EOL><INDENT>token.client.name = form.data['<STR_LIT:name>']<EOL>token.scopes = form.data['<STR_LIT>']<EOL>db.session.commit()<EOL><DEDENT>if len(current_oauth2server.scope_choices()) == <NUM_LIT:0>:<EOL><INDENT>del(form.scopes)<EOL><DEDENT>return render_template(<EOL>"<STR_LIT>",<EOL>token=token,<EOL>form=form,<EOL>show_token=show_token,<EOL>)<EOL>
|
Show token details.
|
f3601:m7
|
@blueprint.route("<STR_LIT>", methods=['<STR_LIT:GET>', ])<EOL>@login_required<EOL>@token_getter(is_personal=False, is_internal=False)<EOL>def token_revoke(token):
|
db.session.delete(token)<EOL>db.session.commit()<EOL>return redirect(url_for('<STR_LIT>'))<EOL>
|
Revoke Authorized Application token.
|
f3601:m8
|
@blueprint.route("<STR_LIT>", methods=['<STR_LIT:GET>', ])<EOL>@login_required<EOL>@token_getter(is_personal=False, is_internal=False)<EOL>def token_permission_view(token):
|
scopes = [current_oauth2server.scopes[x] for x in token.scopes]<EOL>return render_template(<EOL>"<STR_LIT>",<EOL>token=token,<EOL>scopes=scopes,<EOL>)<EOL>
|
Show permission garanted to authorized application token.
|
f3601:m9
|
def proceed(self):
|
self._halted = False<EOL>
|
Unhalt the movement of this particle.
|
f3614:c0:m26
|
def halt(self):
|
self._halted = True<EOL>
|
Halt the movement of this particle.
|
f3614:c0:m27
|
def get_age(self, **kwargs):
|
try:<EOL><INDENT>units = kwargs.get('<STR_LIT>', None)<EOL>if units is None:<EOL><INDENT>return self._age<EOL><DEDENT>units = units.lower()<EOL>if units == "<STR_LIT>":<EOL><INDENT>z = self._age<EOL><DEDENT>elif units == "<STR_LIT>":<EOL><INDENT>z = self._age * <NUM_LIT><EOL><DEDENT>elif units == "<STR_LIT>":<EOL><INDENT>z = self._age * <NUM_LIT> * <NUM_LIT><EOL><DEDENT>elif units == "<STR_LIT>":<EOL><INDENT>z = self._age * <NUM_LIT> * <NUM_LIT> * <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT>return round(z,<NUM_LIT:8>) <EOL><DEDENT>except StandardError:<EOL><INDENT>raise KeyError("<STR_LIT>")<EOL><DEDENT>
|
Returns the particlees age (how long it has been forced) in a variety of units.
Rounded to 8 decimal places.
Parameters:
units (optional) = 'days' (default), 'hours', 'minutes', or 'seconds'
|
f3614:c0:m33
|
def age(self, **kwargs):
|
if kwargs.get('<STR_LIT>', None) is not None:<EOL><INDENT>self._age += kwargs.get('<STR_LIT>')<EOL>return<EOL><DEDENT>if kwargs.get('<STR_LIT>', None) is not None:<EOL><INDENT>self._age += kwargs.get('<STR_LIT>') / <NUM_LIT><EOL>return<EOL><DEDENT>if kwargs.get('<STR_LIT>', None) is not None:<EOL><INDENT>self._age += kwargs.get('<STR_LIT>') / <NUM_LIT> / <NUM_LIT><EOL>return<EOL><DEDENT>if kwargs.get('<STR_LIT>', None) is not None:<EOL><INDENT>self._age += kwargs.get('<STR_LIT>') / <NUM_LIT> / <NUM_LIT> / <NUM_LIT><EOL>return<EOL><DEDENT>raise KeyError("<STR_LIT>")<EOL>
|
Age this particle.
parameters (optional, only one allowed):
days (default)
hours
minutes
seconds
|
f3614:c0:m34
|
def normalized_indexes(self, model_timesteps):
|
<EOL>clean_locs = []<EOL>for i,loc in enumerate(self.locations):<EOL><INDENT>try:<EOL><INDENT>if loc.time == self.locations[i+<NUM_LIT:1>].time:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>clean_locs.append(loc)<EOL><DEDENT><DEDENT>except StandardError:<EOL><INDENT>clean_locs.append(loc)<EOL><DEDENT><DEDENT>if len(clean_locs) == len(model_timesteps):<EOL><INDENT>return [ind for ind,loc in enumerate(self.locations) if loc in clean_locs]<EOL><DEDENT>elif len(model_timesteps) < len(clean_locs):<EOL><INDENT>indexes = [ind for ind,loc in enumerate(self.locations) if loc in clean_locs]<EOL>if len(model_timesteps) == len(indexes):<EOL><INDENT>return indexes<EOL><DEDENT>raise ValueError("<STR_LIT>") <EOL><DEDENT>elif len(model_timesteps) > len(clean_locs):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>
|
This function will normalize the particles locations
to the timestep of the model that was run. This is used
in output, as we should only be outputting the model timestep
that was chosen to be run.
In most cases, the length of the model_timesteps and the
particle's locations will be the same (unless it hits shore).
If they are not the same length pull out of locations the timesteps
that are closest to the model_timesteps
|
f3614:c0:m37
|
def grow(self, amount):
|
self.lifestage_progress += amount<EOL>
|
Grow a particle by a percentage value (0 < x < 1)
When a particle grows past 1, its current lifestage is
complete and it moves onto the next.
The calculation to get the current lifestage index is in get_lifestage_index()
|
f3614:c1:m22
|
def outputstring(self):
|
return "<STR_LIT>" % (self.get_age(units='<STR_LIT>'), self.lifestage_index, (self.lifestage_progress % <NUM_LIT:1>) * <NUM_LIT>)<EOL>
|
For shapefiles, max 254 characters
|
f3614:c1:m24
|
def __init__(self, **kwargs):
|
if kwargs.get("<STR_LIT:file>", None) is not None:<EOL><INDENT>self._file = os.path.normpath(kwargs.pop('<STR_LIT:file>'))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._type = kwargs.pop("<STR_LIT:type>", "<STR_LIT>")<EOL>self._nc = CommonDataset.open(self._file)<EOL>self._bathy_name = kwargs.pop("<STR_LIT>", "<STR_LIT:z>")<EOL>
|
Optional named arguments:
* file (local path or dap to bathymetry netcdf file)
|
f3615:c0:m0
|
def intersect(self, **kwargs):
|
end_point = kwargs.pop('<STR_LIT>')<EOL>depth = self.get_depth(location=end_point)<EOL>if depth < <NUM_LIT:0> and depth > end_point.depth:<EOL><INDENT>inter = True<EOL><DEDENT>else:<EOL><INDENT>inter = False<EOL><DEDENT>return inter<EOL>
|
Intersect Point and Bathymetry
returns bool
|
f3615:c0:m2
|
def react(self, **kwargs):
|
react_type = kwargs.get("<STR_LIT:type>", self._type)<EOL>if react_type == '<STR_LIT>':<EOL><INDENT>return self.__hover(**kwargs)<EOL><DEDENT>elif react_type == '<STR_LIT>':<EOL><INDENT>pass<EOL><DEDENT>elif react_type == '<STR_LIT>':<EOL><INDENT>return self.__reverse(**kwargs)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>
|
The time of recation is ignored hereTime is ignored here
and should be handled by whatever called this function.
|
f3615:c0:m4
|
def __hover(self, **kwargs):
|
end_point = kwargs.pop('<STR_LIT>')<EOL>depth = self.get_depth(location=end_point)<EOL>return Location4D(latitude=end_point.latitude, longitude=end_point.longitude, depth=(depth + <NUM_LIT:1.>))<EOL>
|
This hovers the particle 1m above the bathymetry WHERE IT WOULD HAVE ENDED UP.
This is WRONG and we need to compute the location that it actually hit
the bathymetry and hover 1m above THAT.
|
f3615:c0:m5
|
def __reverse(self, **kwargs):
|
start_point = kwargs.pop('<STR_LIT>')<EOL>return Location4D(latitude=start_point.latitude, longitude=start_point.longitude, depth=start_point.depth)<EOL>
|
If we hit the bathymetry, set the location to where we came from.
|
f3615:c0:m6
|
def calculate_vss(self, method=None):
|
if self.variance == float(<NUM_LIT:0>):<EOL><INDENT>return self.vss<EOL><DEDENT>else:<EOL><INDENT>if method == "<STR_LIT>" or method is None:<EOL><INDENT>return gauss(self.vss, self.variance)<EOL><DEDENT>elif method == "<STR_LIT>":<EOL><INDENT>return uniform(self.vss - self.variance, self.vss + self.variance)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>
|
Calculate the vertical swimming speed of this behavior.
Takes into account the vertical swimming speed and the
variance.
Parameters:
method: "gaussian" (default) or "random"
"random" (vss - variance) < X < (vss + variance)
|
f3618:c0:m1
|
def move(self, particle, u, v, w, modelTimestep, **kwargs):
|
<EOL>if not particle.settled and not particle.dead:<EOL><INDENT>particle.die()<EOL><DEDENT>temp = kwargs.get('<STR_LIT>', None)<EOL>if temp is not None and math.isnan(temp):<EOL><INDENT>temp = None<EOL><DEDENT>particle.temp = temp<EOL>salt = kwargs.get('<STR_LIT>', None)<EOL>if salt is not None and math.isnan(salt):<EOL><INDENT>salt = None<EOL><DEDENT>particle.salt = salt<EOL>u = <NUM_LIT:0><EOL>v = <NUM_LIT:0><EOL>w = <NUM_LIT:0><EOL>result = AsaTransport.distance_from_location_using_u_v_w(u=u, v=v, w=w, timestep=modelTimestep, location=particle.location)<EOL>result['<STR_LIT:u>'] = u<EOL>result['<STR_LIT:v>'] = v<EOL>result['<STR_LIT:w>'] = w<EOL>return result<EOL>
|
I'm dead, so no behaviors should act on me
|
f3619:c1:m1
|
def get_time(self, loc4d=None):
|
if loc4d is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if self.pattern == self.PATTERN_CYCLE:<EOL><INDENT>c = SunCycles.cycles(loc=loc4d)<EOL>if self.cycle == self.CYCLE_SUNRISE:<EOL><INDENT>r = c[SunCycles.RISING]<EOL><DEDENT>elif self.cycle == self.CYCLE_SUNSET:<EOL><INDENT>r = c[SunCycles.SETTING]<EOL><DEDENT>td = timedelta(hours=self.time_delta)<EOL>if self.plus_or_minus == self.HOURS_PLUS:<EOL><INDENT>r = r + td<EOL><DEDENT>elif self.plus_or_minus == self.HOURS_MINUS:<EOL><INDENT>r = r - td<EOL><DEDENT>return r<EOL><DEDENT>elif self.pattern == self.PATTERN_SPECIFICTIME:<EOL><INDENT>return self._time.replace(year=loc4d.time.year, month=loc4d.time.month, day=loc4d.time.day)<EOL><DEDENT>
|
Based on a Location4D object and this Diel object, calculate
the time at which this Diel migration is actually happening
|
f3620:c0:m14
|
def move(self, particle, u, v, w, modelTimestep, **kwargs):
|
logger.debug("<STR_LIT>" % (str(u),str(v),str(w)))<EOL>if (u is None) or (u is not None and math.isnan(u)):<EOL><INDENT>u = particle.last_u()<EOL><DEDENT>if (v is None) or (v is not None and math.isnan(v)):<EOL><INDENT>v = particle.last_v()<EOL><DEDENT>if (w is None) or (w is not None and math.isnan(w)):<EOL><INDENT>w = particle.last_w()<EOL><DEDENT>particle.u_vector = u<EOL>particle.v_vector = v<EOL>particle.w_vector = w<EOL>if particle.halted:<EOL><INDENT>u,v,w = <NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>u += AsaRandom.random() * ((<NUM_LIT:2> * self._horizDisp / modelTimestep) ** <NUM_LIT:0.5>) <EOL>v += AsaRandom.random() * ((<NUM_LIT:2> * self._horizDisp / modelTimestep) ** <NUM_LIT:0.5>) <EOL>w += AsaRandom.random() * ((<NUM_LIT:2> * self._vertDisp / modelTimestep) ** <NUM_LIT:0.5>) <EOL><DEDENT>result = AsaTransport.distance_from_location_using_u_v_w(u=u, v=v, w=w, timestep=modelTimestep, location=particle.location)<EOL>result['<STR_LIT:u>'] = u<EOL>result['<STR_LIT:v>'] = v<EOL>result['<STR_LIT:w>'] = w<EOL>return result<EOL>
|
Returns the lat, lon, H, and velocity of a projected point given a starting
lat and lon (dec deg), a depth (m) below sea surface (positive up), u, v, and w velocity components (m/s), a horizontal and vertical
displacement coefficient (m^2/s) H (m), and a model timestep (s).
GreatCircle calculations are done based on the Vincenty Direct method.
Returns a dict like:
{ 'latitude': x,
'azimuth': x,
'reverse_azimuth': x,
'longitude': x,
'depth': x,
'u': x
'v': x,
'w': x,
'distance': x,
'angle': x,
'vertical_distance': x,
'vertical_angle': x }
|
f3621:c0:m5
|
@classmethod<EOL><INDENT>def export(cls, folder, particles, datetimes):<DEDENT>
|
normalized_locations = [particle.normalized_locations(datetimes) for particle in particles]<EOL>track_coords = []<EOL>for x in xrange(<NUM_LIT:0>, len(datetimes)):<EOL><INDENT>points = MultiPoint([loc[x].point.coords[<NUM_LIT:0>] for loc in normalized_locations])<EOL>track_coords.append(points.centroid.coords[<NUM_LIT:0>])<EOL><DEDENT>ls = LineString(track_coords)<EOL>if not os.path.exists(folder):<EOL><INDENT>os.makedirs(folder)<EOL><DEDENT>filepath = os.path.join(folder, "<STR_LIT>")<EOL>f = open(filepath, "<STR_LIT:wb>")<EOL>f.write(json.dumps(mapping(ls)))<EOL>f.close()<EOL>return filepath<EOL>
|
Export trackline data to GeoJSON file
|
f3624:c1:m0
|
@classmethod<EOL><INDENT>def export(cls, folder, particles, datetimes, summary, **kwargs):<DEDENT>
|
time_units = '<STR_LIT>'<EOL>if not os.path.exists(folder):<EOL><INDENT>os.makedirs(folder)<EOL><DEDENT>filepath = os.path.join(folder, '<STR_LIT>')<EOL>nc = netCDF4.Dataset(filepath, '<STR_LIT:w>')<EOL>nc.createDimension('<STR_LIT:time>', None)<EOL>nc.createDimension('<STR_LIT>', None)<EOL>fillvalue = -<NUM_LIT><EOL>time = nc.createVariable('<STR_LIT:time>', '<STR_LIT:i>', ('<STR_LIT:time>',))<EOL>part = nc.createVariable('<STR_LIT>', '<STR_LIT:i>', ('<STR_LIT>',))<EOL>depth = nc.createVariable('<STR_LIT>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'))<EOL>lat = nc.createVariable('<STR_LIT>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'), fill_value=fillvalue)<EOL>lon = nc.createVariable('<STR_LIT>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'), fill_value=fillvalue)<EOL>salt = nc.createVariable('<STR_LIT>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'), fill_value=fillvalue)<EOL>temp = nc.createVariable('<STR_LIT>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'), fill_value=fillvalue)<EOL>u = nc.createVariable('<STR_LIT:u>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'), fill_value=fillvalue)<EOL>v = nc.createVariable('<STR_LIT:v>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'), fill_value=fillvalue)<EOL>w = nc.createVariable('<STR_LIT:w>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'), fill_value=fillvalue)<EOL>settled = nc.createVariable('<STR_LIT>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'), fill_value=fillvalue)<EOL>dead = nc.createVariable('<STR_LIT>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'), fill_value=fillvalue)<EOL>halted = nc.createVariable('<STR_LIT>', '<STR_LIT:f>', ('<STR_LIT:time>', '<STR_LIT>'), fill_value=fillvalue)<EOL>for j, particle in enumerate(particles):<EOL><INDENT>part[j] = particle.uid<EOL>i = <NUM_LIT:0><EOL>normalized_locations = particle.normalized_locations(datetimes)<EOL>normalized_temps = [x if x is not None and not math.isnan(x) else fillvalue for x in particle.temps]<EOL>normalized_salts = [x if x is not None and not math.isnan(x) else fillvalue for x in particle.salts]<EOL>normalized_u = [x if x is not None and not math.isnan(x) else fillvalue for x in particle.u_vectors]<EOL>normalized_v = [x if x is not None and not math.isnan(x) else fillvalue for x in particle.v_vectors]<EOL>normalized_w = [x if x is not None and not math.isnan(x) else fillvalue for x in particle.w_vectors]<EOL>normalized_settled = [x if x is not None and not math.isnan(x) else fillvalue for x in particle.settles]<EOL>normalized_dead = [x if x is not None and not math.isnan(x) else fillvalue for x in particle.deads]<EOL>normalized_halted = [x if x is not None and not math.isnan(x) else fillvalue for x in particle.halts]<EOL>if len(normalized_locations) != len(normalized_temps):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>normalized_temps = [fillvalue] * len(normalized_locations)<EOL><DEDENT>if len(normalized_locations) != len(normalized_salts):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>normalized_salts = [fillvalue] * len(normalized_locations)<EOL><DEDENT>if len(normalized_locations) != len(normalized_u):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>normalized_u = [fillvalue] * len(normalized_locations)<EOL><DEDENT>if len(normalized_locations) != len(normalized_v):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>normalized_v = [fillvalue] * len(normalized_locations)<EOL><DEDENT>if len(normalized_locations) != len(normalized_w):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>normalized_w = [fillvalue] * len(normalized_locations)<EOL><DEDENT>if len(normalized_locations) != len(normalized_settled):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>normalized_settled = [fillvalue] * len(normalized_locations)<EOL><DEDENT>if len(normalized_locations) != len(normalized_dead):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>normalized_dead = [fillvalue] * len(normalized_locations)<EOL><DEDENT>if len(normalized_locations) != len(normalized_halted):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>normalized_halted = [fillvalue] * len(normalized_locations)<EOL><DEDENT>for loc, _temp, _salt, _u, _v, _w, _settled, _dead, _halted in zip(normalized_locations, normalized_temps, normalized_salts, normalized_u, normalized_v, normalized_w, normalized_settled, normalized_dead, normalized_halted):<EOL><INDENT>if j == <NUM_LIT:0>:<EOL><INDENT>time[i] = int(round(netCDF4.date2num(loc.time, time_units)))<EOL><DEDENT>depth[i, j] = loc.depth<EOL>lat[i, j] = loc.latitude<EOL>lon[i, j] = loc.longitude<EOL>salt[i, j] = _salt<EOL>temp[i, j] = _temp<EOL>u[i, j] = _u<EOL>v[i, j] = _v<EOL>w[i, j] = _w<EOL>settled[i, j] = _settled<EOL>dead[i, j] = _dead<EOL>halted[i, j] = _halted<EOL>i += <NUM_LIT:1><EOL><DEDENT><DEDENT>depth.coordinates = "<STR_LIT>"<EOL>depth.standard_name = "<STR_LIT>"<EOL>depth.units = "<STR_LIT:m>"<EOL>depth.POSITIVE = "<STR_LIT>"<EOL>depth.positive = "<STR_LIT>"<EOL>salt.coordinates = "<STR_LIT>"<EOL>salt.standard_name = "<STR_LIT>"<EOL>salt.units = "<STR_LIT>"<EOL>temp.coordinates = "<STR_LIT>"<EOL>temp.standard_name = "<STR_LIT>"<EOL>temp.units = "<STR_LIT>"<EOL>u.coordinates = "<STR_LIT>"<EOL>u.standard_name = "<STR_LIT>"<EOL>u.units = "<STR_LIT>"<EOL>v.coordinates = "<STR_LIT>"<EOL>v.standard_name = "<STR_LIT>"<EOL>v.units = "<STR_LIT>"<EOL>w.coordinates = "<STR_LIT>"<EOL>w.standard_name = "<STR_LIT>"<EOL>w.units = "<STR_LIT>"<EOL>settled.coordinates = "<STR_LIT>"<EOL>settled.description = "<STR_LIT>"<EOL>settled.standard_name = "<STR_LIT>"<EOL>dead.coordinates = "<STR_LIT>"<EOL>dead.description = "<STR_LIT>"<EOL>dead.standard_name = "<STR_LIT>"<EOL>halted.coordinates = "<STR_LIT>"<EOL>halted.description = "<STR_LIT>"<EOL>halted.standard_name = "<STR_LIT>"<EOL>time.units = time_units<EOL>time.standard_name = "<STR_LIT:time>"<EOL>lat.units = "<STR_LIT>"<EOL>lon.units = "<STR_LIT>"<EOL>part.cf_role = "<STR_LIT>"<EOL>nc.featureType = "<STR_LIT>"<EOL>nc.summary = str(summary)<EOL>for key in kwargs:<EOL><INDENT>nc.__setattr__(key, kwargs.get(key))<EOL><DEDENT>nc.sync()<EOL>nc.close()<EOL>
|
Export particle data to CF trajectory convention
netcdf file
|
f3624:c3:m0
|
@classmethod<EOL><INDENT>def export(cls, folder, particles, datetimes):<DEDENT>
|
if not os.path.exists(folder):<EOL><INDENT>os.makedirs(folder)<EOL><DEDENT>particle_path = os.path.join(folder, '<STR_LIT>')<EOL>f = open(particle_path, "<STR_LIT:wb>")<EOL>pickle.dump(particles, f)<EOL>f.close()<EOL>datetimes_path = os.path.join(folder, '<STR_LIT>')<EOL>f = open(datetimes_path, "<STR_LIT:wb>")<EOL>pickle.dump(datetimes, f)<EOL>f.close()<EOL>
|
Export particle and datetime data to Pickled objects.
This can be used to debug or to generate different output
in the future.
|
f3624:c4:m0
|
def compute_probability(trajectory_files, bbox=None,<EOL>nx=None, ny=None, method='<STR_LIT>', parameter='<STR_LIT:location>'):
|
xarray = np.linspace(float(bbox[<NUM_LIT:0>]), float(bbox[<NUM_LIT:2>]), int(nx)+<NUM_LIT:1>)<EOL>yarray = np.linspace(float(bbox[<NUM_LIT:1>]), float(bbox[<NUM_LIT:3>]), int(ny)+<NUM_LIT:1>)<EOL>if method == '<STR_LIT>':<EOL><INDENT>prob = np.zeros((ny, nx))<EOL>for runfile in trajectory_files:<EOL><INDENT>run = netCDF4.Dataset(runfile)<EOL>if parameter == '<STR_LIT:location>':<EOL><INDENT>lat = run.variables['<STR_LIT>'][:].flatten()<EOL>lon = run.variables['<STR_LIT>'][:].flatten()<EOL>column_i, row_i = [], []<EOL>for clon, clat in zip(lon, lat):<EOL><INDENT>column_i.append(bisect.bisect(xarray, clon))<EOL>row_i.append(bisect.bisect(yarray, clat))<EOL>try:<EOL><INDENT>prob[row_i[-<NUM_LIT:1>], column_i[-<NUM_LIT:1>]] += <NUM_LIT:1><EOL><DEDENT>except StandardError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>elif parameter == '<STR_LIT>':<EOL><INDENT>for i in range(run.variables['<STR_LIT:time>'].shape[<NUM_LIT:0>]):<EOL><INDENT>settle_index = np.where(<EOL>run.variables['<STR_LIT>'][i, :] == <NUM_LIT:1>)<EOL>if len(settle_index[<NUM_LIT:0>]) > <NUM_LIT:0>:<EOL><INDENT>lat = run.variables['<STR_LIT>'][i,<EOL>settle_index[<NUM_LIT:0>]].flatten()<EOL>lon = run.variables['<STR_LIT>'][i,<EOL>settle_index[<NUM_LIT:0>]].flatten()<EOL>column_i, row_i = [], []<EOL>for clon, clat in zip(lon, lat):<EOL><INDENT>column_i.append(bisect.bisect(xarray, clon))<EOL>row_i.append(bisect.bisect(yarray, clat))<EOL>try:<EOL><INDENT>prob[row_i[-<NUM_LIT:1>], column_i[-<NUM_LIT:1>]] += <NUM_LIT:1><EOL><DEDENT>except StandardError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>shape = run.variables['<STR_LIT:time>'].shape<EOL>prob = prob / (shape[<NUM_LIT:0>] * len(trajectory_files))<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>prob = []<EOL>for i, runfile in enumerate(trajectory_files):<EOL><INDENT>prob.append(np.zeros((ny, nx)))<EOL>run = netCDF4.Dataset(runfile)<EOL>if parameter == '<STR_LIT:location>':<EOL><INDENT>lat = run.variables['<STR_LIT>'][:].flatten()<EOL>lon = run.variables['<STR_LIT>'][:].flatten()<EOL><DEDENT>elif parameter == '<STR_LIT>':<EOL><INDENT>settle_index = np.where(<EOL>run.variables['<STR_LIT>'][-<NUM_LIT:1>, :] == <NUM_LIT:1>)[<NUM_LIT:0>]<EOL>lat = run.variables['<STR_LIT>'][-<NUM_LIT:1>, settle_index].flatten()<EOL>lon = run.variables['<STR_LIT>'][-<NUM_LIT:1>, settle_index].flatten()<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>column_i, row_i = [], []<EOL>for clon, clat in zip(lon, lat):<EOL><INDENT>column_i.append(bisect.bisect(xarray, clon))<EOL>row_i.append(bisect.bisect(yarray, clat))<EOL>try:<EOL><INDENT>if prob[i][row_i[-<NUM_LIT:1>], column_i[-<NUM_LIT:1>]] == <NUM_LIT:0>:<EOL><INDENT>prob[i][row_i[-<NUM_LIT:1>], column_i[-<NUM_LIT:1>]] = <NUM_LIT:1><EOL><DEDENT><DEDENT>except StandardError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>prob2 = np.zeros((ny, nx))<EOL>for run in prob:<EOL><INDENT>prob2 = run + prob2<EOL><DEDENT>prob = prob2 / len(prob)<EOL><DEDENT>return prob<EOL>
|
This function creates a probability (stochastic) grid
for trajectory model data using 'overall' method (based
on normalization by nsteps * nparticles) or 'run' method
(based on normalization by run).
probability_grid = compute_probability([myfile1.nc, myfile2.nc],
bbox = [-75, 23, -60, 45],
nx = 1000, ny = 1000,
method = 'overall')
stoch.compute_probability(['/media/sf_Python/trajectories.nc'],bbox=[-148,60,-146,61],nx=500,ny=500,method='overall',parameter='settlement')
|
f3625:m0
|
def compute_probability_settle(trajectory_files, bbox=None,<EOL>nx=<NUM_LIT:1000>, ny=<NUM_LIT:1000>, method='<STR_LIT>'):
|
prob = compute_probability(trajectory_files,<EOL>bbox,<EOL>nx, ny,<EOL>method,<EOL>parameter='<STR_LIT>',<EOL>)<EOL>return prob<EOL>
|
This function creates a probability (stochastic) grid
for trajectory model data based on settlement location,
normalized by run.
probability_grid = compute_probability_settle([myfile1.nc, myfile2.nc],
bbox = [-75, 23, -60, 45],
nx = 1000, ny = 1000,
method='overall')
|
f3625:m1
|
def export_probability(outputname, **kwargs):
|
bbox = kwargs.get('<STR_LIT>', None)<EOL>nx, ny = kwargs.get('<STR_LIT>', None), kwargs.get('<STR_LIT>', None)<EOL>if bbox == None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if nx == None or ny == None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>prob = compute_probability(**kwargs)<EOL>export_grid(outputname, prob, bbox, nx, ny)<EOL>
|
Calculate probability and export to gis raster/grid
format.
export_probability(prob_out,
trajectory_files = [myfiles1.nc, myfiles2.nc],
bbox = [-75, 23, -60, 45],
nx = 1000, ny = 1000,
method = 'overall')
|
f3625:m3
|
@classmethod<EOL><INDENT>def cycles(cls, **kwargs):<DEDENT>
|
if "<STR_LIT>" not in kwargs:<EOL><INDENT>if "<STR_LIT>" not in kwargs:<EOL><INDENT>if "<STR_LIT>" not in kwargs or "<STR_LIT>" not in kwargs:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>lat = kwargs.get("<STR_LIT>")<EOL>lon = kwargs.get("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>lat = kwargs.get("<STR_LIT>").y<EOL>lon = kwargs.get("<STR_LIT>").x<EOL><DEDENT>if "<STR_LIT:time>" not in kwargs:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>time = kwargs.get("<STR_LIT:time>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>lat = kwargs.get("<STR_LIT>").latitude<EOL>lon = kwargs.get("<STR_LIT>").longitude<EOL>time = kwargs.get("<STR_LIT>").time<EOL><DEDENT>if time.tzinfo is None:<EOL><INDENT>time = time.replace(tzinfo=pytz.utc)<EOL>original_zone = pytz.utc<EOL><DEDENT>else:<EOL><INDENT>original_zone = time.tzinfo<EOL><DEDENT>local_jd = time.timetuple().tm_yday<EOL>utc_jd = time.astimezone(pytz.utc).timetuple().tm_yday<EOL>comp = cmp(utc_jd, local_jd)<EOL>if comp == <NUM_LIT:1>:<EOL><INDENT>utc_jd -= <NUM_LIT:1><EOL><DEDENT>elif comp == -<NUM_LIT:1>:<EOL><INDENT>utc_jd += <NUM_LIT:1><EOL><DEDENT>time = time.replace(hour=<NUM_LIT:0>, minute=<NUM_LIT:0>, second=<NUM_LIT:0>, microsecond=<NUM_LIT:0>)<EOL>rising_h, rising_m = cls._calc(jd=utc_jd, lat=lat, lon=lon, stage=cls.RISING)<EOL>setting_h, setting_m = cls._calc(jd=utc_jd, lat=lat, lon=lon, stage=cls.SETTING)<EOL>rising = time.replace(tzinfo=pytz.utc) + timedelta(hours=rising_h, minutes=rising_m)<EOL>setting = time.replace(tzinfo=pytz.utc) + timedelta(hours=setting_h, minutes=setting_m)<EOL>if setting < rising:<EOL><INDENT>setting = setting + timedelta(hours=<NUM_LIT>)<EOL><DEDENT>rising = rising.astimezone(original_zone)<EOL>setting = setting.astimezone(original_zone)<EOL>return { cls.RISING : rising, cls.SETTING : setting}<EOL>
|
Classmethod for convienence in returning both the sunrise and sunset
based on a location and date. Always calculates the sunrise and sunset on the
given date, no matter the time passed into the function in the datetime object.
Parameters:
loc = Location4D (object)
OR
point = Shapely point (object)
time = datetime in UTC (object)
OR
lat = latitude (float)
lon = longitude (float)
time = datetime in UTC (object)
Returns:
{ 'sunrise': datetime in UTC, 'sunset': datetime in UTC }
Sources:
http://williams.best.vwh.net/sunrise_sunset_example.htm
|
f3626:c0:m0
|
@classmethod<EOL><INDENT>def _calc(cls, **kwargs):<DEDENT>
|
zenith = <NUM_LIT> <EOL>jd = kwargs.get("<STR_LIT>", None)<EOL>lat = kwargs.get("<STR_LIT>", None)<EOL>lon = kwargs.get("<STR_LIT>", None)<EOL>stage = kwargs.get("<STR_LIT>", None)<EOL>if jd is None or stage is None or lat is None or lon is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if stage != SunCycles.RISING and stage != SunCycles.SETTING:<EOL><INDENT>raise ValueError("<STR_LIT>" % (SunCycles.RISING, SunCycles.SETTING))<EOL><DEDENT>longhr = lon / <NUM_LIT><EOL>if stage == SunCycles.RISING:<EOL><INDENT>apx = jd + ( (<NUM_LIT:6> - longhr) / <NUM_LIT> )<EOL><DEDENT>elif stage == SunCycles.SETTING:<EOL><INDENT>apx = jd + ( (<NUM_LIT> - longhr) / <NUM_LIT> )<EOL><DEDENT>sun_mean_anom = ( <NUM_LIT> * apx ) - <NUM_LIT> <EOL>sun_lon = sun_mean_anom + (<NUM_LIT> * np.sin( np.radians(sun_mean_anom) ))+ (<NUM_LIT> * np.sin( np.radians(<NUM_LIT:2> * sun_mean_anom) )) + <NUM_LIT><EOL>if sun_lon > <NUM_LIT>:<EOL><INDENT>sun_lon = sun_lon - <NUM_LIT><EOL><DEDENT>elif sun_lon < <NUM_LIT:0>:<EOL><INDENT>sun_lon = sun_lon + <NUM_LIT><EOL><DEDENT>right_ascension = np.degrees(np.arctan( <NUM_LIT> * np.tan( np.radians(sun_lon) ) )) <EOL>if right_ascension > <NUM_LIT>:<EOL><INDENT>right_ascension = right_ascension - <NUM_LIT><EOL><DEDENT>elif right_ascension < <NUM_LIT:0>:<EOL><INDENT>right_ascension = right_ascension + <NUM_LIT><EOL><DEDENT>lQuad = <NUM_LIT> * np.floor(sun_lon / <NUM_LIT>)<EOL>raQuad = <NUM_LIT> * np.floor(right_ascension / <NUM_LIT>)<EOL>right_ascension = right_ascension + ( lQuad - raQuad)<EOL>right_ascension = right_ascension / <NUM_LIT> <EOL>sinDecl = <NUM_LIT> * np.sin( np.radians(sun_lon) )<EOL>cosDecl = np.cos( np.arcsin( sinDecl ) )<EOL>cosHr = (np.cos( np.radians(zenith) ) - ( sinDecl * np.sin(np.radians(lat)) ))/ ( cosDecl * np.cos( np.radians(lat) ) )<EOL>if cosHr > <NUM_LIT:1>: <EOL><INDENT>return -<NUM_LIT:1>, -<NUM_LIT:1><EOL><DEDENT>elif cosHr < -<NUM_LIT:1>: <EOL><INDENT>return -<NUM_LIT:1>, -<NUM_LIT:1><EOL><DEDENT>elif stage == SunCycles.RISING: <EOL><INDENT>hr = <NUM_LIT> - np.degrees(np.arccos(cosHr))<EOL><DEDENT>elif stage == SunCycles.SETTING: <EOL><INDENT>hr = np.degrees(np.arccos(cosHr))<EOL><DEDENT>hr = hr / <NUM_LIT> <EOL>localTime = hr + right_ascension - ( <NUM_LIT> * apx ) - <NUM_LIT><EOL>UTtime = localTime - longhr <EOL>if UTtime < <NUM_LIT:0>:<EOL><INDENT>UTtime = UTtime + <NUM_LIT><EOL><DEDENT>elif UTtime > <NUM_LIT>:<EOL><INDENT>UTtime = UTtime - <NUM_LIT><EOL><DEDENT>hour = np.floor(UTtime)<EOL>minute = (UTtime - hour) * <NUM_LIT><EOL>if minute == <NUM_LIT>:<EOL><INDENT>hour = hour + <NUM_LIT:1><EOL>minute = <NUM_LIT:0><EOL><DEDENT>return hour, minute<EOL>
|
Calculate sunrise or sunset based on:
Parameters:
jd: Julian Day
lat: latitude
lon: longitude
stage: sunrise or sunset
|
f3626:c0:m1
|
@classmethod<EOL><INDENT>def get_time_objects_from_model_timesteps(cls, times, start):<DEDENT>
|
modelTimestep = []<EOL>newtimes = []<EOL>for i in xrange(<NUM_LIT:0>, len(times)):<EOL><INDENT>try:<EOL><INDENT>modelTimestep.append(times[i+<NUM_LIT:1>] - times[i])<EOL><DEDENT>except StandardError:<EOL><INDENT>modelTimestep.append(times[i] - times[i-<NUM_LIT:1>])<EOL><DEDENT>newtimes.append(start + timedelta(seconds=times[i]))<EOL><DEDENT>return (modelTimestep, newtimes)<EOL>
|
Calculate the datetimes of the model timesteps
times should start at 0 and be in seconds
|
f3627:c0:m0
|
@classmethod<EOL><INDENT>def fill_polygon_with_points(cls, goal=None, polygon=None):<DEDENT>
|
if goal is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if polygon is None or (not isinstance(polygon, Polygon) and not isinstance(polygon, MultiPolygon)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>minx = polygon.bounds[<NUM_LIT:0>] <EOL>maxx = polygon.bounds[<NUM_LIT:2>] <EOL>miny = polygon.bounds[<NUM_LIT:1>] <EOL>maxy = polygon.bounds[<NUM_LIT:3>] <EOL>points = []<EOL>now = time.time()<EOL>while len(points) < goal:<EOL><INDENT>random_x = random.uniform(minx, maxx)<EOL>random_y = random.uniform(miny, maxy)<EOL>p = Point(random_x, random_y)<EOL>if p.within(polygon):<EOL><INDENT>points.append(p)<EOL><DEDENT><DEDENT>logger.info("<STR_LIT>" % (time.time() - now))<EOL>return points<EOL>
|
Fill a shapely polygon with X number of points
|
f3627:c0:m1
|
@classmethod<EOL><INDENT>def distance_from_location_using_u_v_w(cls, u=None, v=None, w=None, timestep=None, location=None):<DEDENT>
|
<EOL>distance_horiz = <NUM_LIT:0><EOL>azimuth = <NUM_LIT:0><EOL>angle = <NUM_LIT:0><EOL>depth = location.depth<EOL>if u is not <NUM_LIT:0> and v is not <NUM_LIT:0>:<EOL><INDENT>s_and_d = AsaMath.speed_direction_from_u_v(u=u,v=v) <EOL>distance_horiz = s_and_d['<STR_LIT>'] * timestep <EOL>angle = s_and_d['<STR_LIT>']<EOL>azimuth = AsaMath.math_angle_to_azimuth(angle=angle)<EOL><DEDENT>distance_vert = <NUM_LIT:0.><EOL>if w is not None:<EOL><INDENT>distance_vert = w * timestep<EOL>depth += distance_vert <EOL><DEDENT>if distance_horiz != <NUM_LIT:0>:<EOL><INDENT>vertical_angle = math.degrees(math.atan(distance_vert / distance_horiz))<EOL>gc_result = AsaGreatCircle.great_circle(distance=distance_horiz, azimuth=azimuth, start_point=location) <EOL><DEDENT>else:<EOL><INDENT>vertical_angle = <NUM_LIT:0.><EOL>if distance_vert < <NUM_LIT:0>:<EOL><INDENT>vertical_angle = <NUM_LIT><EOL><DEDENT>elif distance_vert > <NUM_LIT:0>:<EOL><INDENT>vertical_angle = <NUM_LIT><EOL><DEDENT>gc_result = { '<STR_LIT>': location.latitude, '<STR_LIT>': location.longitude, '<STR_LIT>': <NUM_LIT:0> }<EOL><DEDENT>gc_result['<STR_LIT>'] = azimuth<EOL>gc_result['<STR_LIT>'] = depth<EOL>gc_result['<STR_LIT>'] = distance_horiz<EOL>gc_result['<STR_LIT>'] = angle<EOL>gc_result['<STR_LIT>'] = distance_vert<EOL>gc_result['<STR_LIT>'] = vertical_angle<EOL>return gc_result<EOL>
|
Calculate the greate distance from a location using u, v, and w.
u, v, and w must be in the same units as the timestep. Stick with seconds.
|
f3627:c0:m2
|
def get_capabilities(self):
|
return None<EOL>
|
Gets capabilities.
Queries WFS server or file for its capabilities (or simulated capabilities).
|
f3628:c0:m5
|
def get_feature_type_info(self):
|
return None<EOL>
|
Gets FeatureType as a python dict.
Transforms feature_name info into python dict.
|
f3628:c0:m6
|
def get_geoms_for_bounds(self, bounds):
|
pass<EOL>
|
Helper method to get geometries withiin a certain bounds.
|
f3628:c0:m7
|
def index(self, point=None, spatialbuffer=None):
|
pass<EOL>
|
This queries the shapefile around a buffer of a point
The results of this spatial query are used for shoreline detection.
Using the entire shapefile without the spatial query takes over
30 times the time with world land polygons.
|
f3628:c0:m8
|
def intersect(self, **kwargs):
|
ls = None<EOL>if "<STR_LIT>" in kwargs:<EOL><INDENT>ls = kwargs.pop('<STR_LIT>')<EOL>spoint = Point(ls.coords[<NUM_LIT:0>])<EOL>epoint = Point(ls.coords[-<NUM_LIT:1>])<EOL><DEDENT>elif "<STR_LIT>" and "<STR_LIT>" in kwargs:<EOL><INDENT>spoint = kwargs.get('<STR_LIT>')<EOL>epoint = kwargs.get('<STR_LIT>')<EOL>ls = LineString(list(spoint.coords) + list(epoint.coords))<EOL><DEDENT>elif "<STR_LIT>" in kwargs:<EOL><INDENT>spoint = kwargs.get('<STR_LIT>')<EOL>epoint = None<EOL>ls = LineString(list(spoint.coords) + list(spoint.coords))<EOL><DEDENT>else:<EOL><INDENT>raise TypeError( "<STR_LIT>" )<EOL><DEDENT>inter = False<EOL>if self._spatial_query_object is None or (self._spatial_query_object and not ls.within(self._spatial_query_object)):<EOL><INDENT>self.index(point=spoint)<EOL><DEDENT>for element in self._geoms:<EOL><INDENT>prepped_element = prep(element)<EOL>if prepped_element.contains(spoint):<EOL><INDENT>if epoint is None:<EOL><INDENT>return {'<STR_LIT>': spoint, '<STR_LIT>': None}<EOL><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LIT>' % (spoint.envelope, epoint.envelope, element.envelope))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if epoint is None:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>inter = ls.intersection(element)<EOL>if inter:<EOL><INDENT>if isinstance(inter, MultiLineString):<EOL><INDENT>inter = inter.geoms[<NUM_LIT:0>]<EOL><DEDENT>inter = Point(inter.coords[<NUM_LIT:0>])<EOL>smaller_int = inter.buffer(self._spatialbuffer)<EOL>shorelines = element.exterior.intersection(smaller_int)<EOL>if isinstance(shorelines, LineString):<EOL><INDENT>shorelines = [shorelines]<EOL><DEDENT>else:<EOL><INDENT>shorelines = list(shorelines)<EOL><DEDENT>for shore_segment in shorelines:<EOL><INDENT>if ls.touches(shore_segment):<EOL><INDENT>break<EOL><DEDENT><DEDENT>return {'<STR_LIT>': Point(inter.x, inter.y, <NUM_LIT:0>), '<STR_LIT>': shore_segment or None}<EOL><DEDENT><DEDENT>return None<EOL>
|
Intersect a Line or Point Collection and the Shoreline
Returns the point of intersection along the coastline
Should also return a linestring buffer around the interseciton point
so we can calculate the direction to bounce a particle.
|
f3628:c0:m9
|
def react(self, **kwargs):
|
if self._type == "<STR_LIT>":<EOL><INDENT>print("<STR_LIT>")<EOL>return self.__bounce(**kwargs)<EOL><DEDENT>elif self._type == "<STR_LIT>":<EOL><INDENT>return self.__reverse(**kwargs)<EOL><DEDENT>else:<EOL><INDENT>return kwargs.get('<STR_LIT>')<EOL>print("<STR_LIT>")<EOL><DEDENT>
|
Bounce off of a shoreline
feature = Linestring of two points, being the line segment the particle hit.
angle = decimal degrees from 0 (x-axis), couter-clockwise (math style)
|
f3628:c0:m10
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.