instance_id
stringlengths 10
57
| file_changes
listlengths 1
15
| repo
stringlengths 7
53
| base_commit
stringlengths 40
40
| problem_statement
stringlengths 11
52.5k
| patch
stringlengths 251
7.06M
|
|---|---|---|---|---|---|
0b01001001__spectree-64
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "setup.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"spectree/utils.py:parse_params"
],
"edited_modules": [
"spectree/utils.py:parse_params"
]
},
"file": "spectree/utils.py"
}
] |
0b01001001/spectree
|
a091fab020ac26548250c907bae0855273a98778
|
[BUG]description for query paramters can not show in swagger ui
Hi, when I add a description for a schema used in query, it can not show in swagger ui but can show in Redoc
```py
@HELLO.route('/', methods=['GET'])
@api.validate(query=HelloForm)
def hello():
"""
hello 注释
:return:
"""
return 'ok'
class HelloForm(BaseModel):
"""
hello表单
"""
user: str # 用户名称
msg: str = Field(description='msg test', example='aa')
index: int
data: HelloGetListForm
list: List[HelloListForm]
```


|
diff --git a/setup.py b/setup.py
index 1b3cb64..4ef21e6 100644
--- a/setup.py
+++ b/setup.py
@@ -14,7 +14,7 @@ with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f:
setup(
name='spectree',
- version='0.3.7',
+ version='0.3.8',
author='Keming Yang',
author_email='kemingy94@gmail.com',
description=('generate OpenAPI document and validate request&response '
diff --git a/spectree/utils.py b/spectree/utils.py
index bb5698d..73d6c71 100644
--- a/spectree/utils.py
+++ b/spectree/utils.py
@@ -54,6 +54,7 @@ def parse_params(func, params, models):
'in': 'query',
'schema': schema,
'required': name in query.get('required', []),
+ 'description': schema.get('description', ''),
})
if hasattr(func, 'headers'):
@@ -64,6 +65,7 @@ def parse_params(func, params, models):
'in': 'header',
'schema': schema,
'required': name in headers.get('required', []),
+ 'description': schema.get('description', ''),
})
if hasattr(func, 'cookies'):
@@ -74,6 +76,7 @@ def parse_params(func, params, models):
'in': 'cookie',
'schema': schema,
'required': name in cookies.get('required', []),
+ 'description': schema.get('description', ''),
})
return params
|
12rambau__sepal_ui-411
|
[
{
"changes": {
"added_entities": [
"sepal_ui/sepalwidgets/inputs.py:DatePicker.disable"
],
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"sepal_ui/sepalwidgets/inputs.py:DatePicker"
]
},
"file": "sepal_ui/sepalwidgets/inputs.py"
}
] |
12rambau/sepal_ui
|
179bd8d089275c54e94a7614be7ed03d298ef532
|
add a disabled trait on the datepicker
I'm currently coding it in a module and the process of disabling a datepicker is uterly boring. I think we could add an extra trait to the layout and pilot the enabling and disabling directly from the built-in widget
```python
self.w_start = sw.DatePicker(label="start", v_model=None)
# disable both the slots (hidden to everyone) and the menu
self.w_start.menu.v_slots[0]["children"].disabled = True
self.w_start.menu.disabled = True
```
|
diff --git a/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst b/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst
index 1a982afb..867227cb 100644
--- a/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst
+++ b/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst
@@ -8,6 +8,7 @@ sepal\_ui.sepalwidgets.DatePicker
.. autosummary::
~DatePicker.menu
+ ~DatePicker.disabled
.. rubric:: Methods
@@ -15,5 +16,8 @@ sepal\_ui.sepalwidgets.DatePicker
:nosignatures:
~Datepicker.close_menu
+ ~DatePicker.disable
-.. automethod:: sepal_ui.sepalwidgets.DatePicker.close_menu
\ No newline at end of file
+.. automethod:: sepal_ui.sepalwidgets.DatePicker.close_menu
+
+.. automethod:: sepal_ui.sepalwidgets.DatePicker.disable
\ No newline at end of file
diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py
index 3ad7f1a9..68b81746 100644
--- a/sepal_ui/sepalwidgets/inputs.py
+++ b/sepal_ui/sepalwidgets/inputs.py
@@ -1,7 +1,7 @@
from pathlib import Path
import ipyvuetify as v
-from traitlets import link, Int, Any, List, observe, Dict, Unicode
+from traitlets import link, Int, Any, List, observe, Dict, Unicode, Bool
from ipywidgets import jslink
import pandas as pd
import ee
@@ -40,6 +40,9 @@ class DatePicker(v.Layout, SepalWidget):
menu = None
"v.Menu: the menu widget to display the datepicker"
+ disabled = Bool(False).tag(sync=True)
+ "traitlets.Bool: the disabled status of the Datepicker object"
+
def __init__(self, label="Date", **kwargs):
# create the widgets
@@ -93,6 +96,14 @@ class DatePicker(v.Layout, SepalWidget):
return
+ @observe("disabled")
+ def disable(self, change):
+ """A method to disabled the appropriate components in the datipkcer object"""
+
+ self.menu.v_slots[0]["children"].disabled = self.disabled
+
+ return
+
class FileInput(v.Flex, SepalWidget):
"""
|
12rambau__sepal_ui-416
|
[
{
"changes": {
"added_entities": [
"sepal_ui/sepalwidgets/app.py:DrawerItem.add_notif",
"sepal_ui/sepalwidgets/app.py:DrawerItem.remove_notif"
],
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/app.py:DrawerItem.__init__",
"sepal_ui/sepalwidgets/app.py:DrawerItem._on_click"
],
"edited_modules": [
"sepal_ui/sepalwidgets/app.py:DrawerItem"
]
},
"file": "sepal_ui/sepalwidgets/app.py"
}
] |
12rambau/sepal_ui
|
8b76805db051d6d15024bd9ec2d78502cd92132e
|
Interact with navigation drawers
Sometimes is useful to pass some data from the module model to the app environment and so far we do not have this implementation.
We can add two simple methods to the drawers so they can update their state with icons, badges, and so.
|
diff --git a/docs/source/modules/sepal_ui.sepalwidgets.DrawerItem.rst b/docs/source/modules/sepal_ui.sepalwidgets.DrawerItem.rst
index a3280cd3..22b87b44 100644
--- a/docs/source/modules/sepal_ui.sepalwidgets.DrawerItem.rst
+++ b/docs/source/modules/sepal_ui.sepalwidgets.DrawerItem.rst
@@ -7,7 +7,9 @@ sepal\_ui.sepalwidgets.DrawerItem
.. autosummary::
- ~DrawerItem.rt
+ ~DrawerItem.rt
+ ~DrawerItem.alert
+ ~DrawerItem.alert_badge
.. rubric:: Methods
@@ -15,5 +17,11 @@ sepal\_ui.sepalwidgets.DrawerItem
:nosignatures:
~DrawerItem.display_tile
+ ~DrawerItem.add_notif
+ ~DrawerItem.remove_notif
-.. automethod:: sepal_ui.sepalwidgets.DrawerItem.display_tile
\ No newline at end of file
+.. automethod:: sepal_ui.sepalwidgets.DrawerItem.display_tile
+
+.. automethod:: sepal_ui.sepalwidgets.DrawerItem.add_notif
+
+.. automethod:: sepal_ui.sepalwidgets.DrawerItem.remove_notif
\ No newline at end of file
diff --git a/sepal_ui/sepalwidgets/app.py b/sepal_ui/sepalwidgets/app.py
index a1aff843..2a87de83 100644
--- a/sepal_ui/sepalwidgets/app.py
+++ b/sepal_ui/sepalwidgets/app.py
@@ -1,3 +1,4 @@
+from traitlets import link, Bool, observe
from functools import partial
from datetime import datetime
@@ -73,12 +74,29 @@ class DrawerItem(v.ListItem, SepalWidget):
card (str, optional): the mount_id of tiles in the app
href (str, optional): the absolute link to an external web page
kwargs (optional): any parameter from a v.ListItem. If set, '_metadata', 'target', 'link' and 'children' will be overwritten.
+ model (optional): sepalwidget model where is defined the bin_var trait
+ bind_var (optional): required when model is selected. Trait to link with 'alert' self trait parameter
"""
rt = None
"sw.ResizeTrigger: the trigger to resize maps and other javascript object when jumping from a tile to another"
- def __init__(self, title, icon=None, card=None, href=None, **kwargs):
+ alert = Bool(False).tag(sync=True)
+ "Bool: trait to control visibility of an alert in the drawer item"
+
+ alert_badge = None
+ "v.ListItemAction: red circle to display in the drawer"
+
+ def __init__(
+ self,
+ title,
+ icon=None,
+ card=None,
+ href=None,
+ model=None,
+ bind_var=None,
+ **kwargs
+ ):
# set the resizetrigger
self.rt = js.rt
@@ -108,6 +126,45 @@ class DrawerItem(v.ListItem, SepalWidget):
# call the constructor
super().__init__(**kwargs)
+ # cannot be set as a class member because it will be shared with all
+ # the other draweritems.
+ self.alert_badge = v.ListItemAction(
+ children=[v.Icon(children=["fas fa-circle"], x_small=True, color="red")]
+ )
+
+ if model:
+ if not bind_var:
+ raise Exception(
+ "You have selected a model, you need a trait to bind with drawer."
+ )
+
+ link((model, bind_var), (self, "alert"))
+
+ @observe("alert")
+ def add_notif(self, change):
+ """Add a notification alert to drawer"""
+
+ if change["new"]:
+ if self.alert_badge not in self.children:
+ new_children = self.children[:]
+ new_children.append(self.alert_badge)
+ self.children = new_children
+ else:
+ self.remove_notif()
+
+ return
+
+ def remove_notif(self):
+ """Remove notification alert"""
+
+ if self.alert_badge in self.children:
+ new_children = self.children[:]
+ new_children.remove(self.alert_badge)
+
+ self.children = new_children
+
+ return
+
def display_tile(self, tiles):
"""
Display the apropriate tiles when the item is clicked.
@@ -138,6 +195,9 @@ class DrawerItem(v.ListItem, SepalWidget):
# change the current item status
self.input_value = True
+ # Remove notification
+ self.remove_notif()
+
return self
|
12rambau__sepal_ui-418
|
[
{
"changes": {
"added_entities": [
"sepal_ui/sepalwidgets/inputs.py:DatePicker.check_date",
"sepal_ui/sepalwidgets/inputs.py:DatePicker.is_valid_date"
],
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/inputs.py:DatePicker.__init__"
],
"edited_modules": [
"sepal_ui/sepalwidgets/inputs.py:DatePicker"
]
},
"file": "sepal_ui/sepalwidgets/inputs.py"
}
] |
12rambau/sepal_ui
|
8b76805db051d6d15024bd9ec2d78502cd92132e
|
Can't instantiate a sw.DatePicker with initial v_model
Is not possible to instantiate the sepal DatePicker with an initially given date through the `v_model` parameter
|
diff --git a/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst b/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst
index 867227cb..322cca23 100644
--- a/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst
+++ b/docs/source/modules/sepal_ui.sepalwidgets.DatePicker.rst
@@ -9,6 +9,7 @@ sepal\_ui.sepalwidgets.DatePicker
~DatePicker.menu
~DatePicker.disabled
+ ~DatePicker.date_text
.. rubric:: Methods
@@ -17,7 +18,13 @@ sepal\_ui.sepalwidgets.DatePicker
~Datepicker.close_menu
~DatePicker.disable
+ ~DatePicker.is_valid_date
+ ~DatePicker.check_date
.. automethod:: sepal_ui.sepalwidgets.DatePicker.close_menu
-.. automethod:: sepal_ui.sepalwidgets.DatePicker.disable
\ No newline at end of file
+.. automethod:: sepal_ui.sepalwidgets.DatePicker.disable
+
+.. automethod:: sepal_ui.sepalwidgets.DatePicker.check_date
+
+.. autofunction:: sepal_ui.sepalwidgets.DatePicker.disable
\ No newline at end of file
diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py
index 7d003229..bf1adf0b 100644
--- a/sepal_ui/sepalwidgets/inputs.py
+++ b/sepal_ui/sepalwidgets/inputs.py
@@ -1,4 +1,5 @@
from pathlib import Path
+from datetime import datetime
import ipyvuetify as v
from traitlets import link, Int, Any, List, observe, Dict, Unicode, Bool
@@ -40,6 +41,9 @@ class DatePicker(v.Layout, SepalWidget):
menu = None
"v.Menu: the menu widget to display the datepicker"
+ date_text = None
+ "v.TextField: the text field of the datepicker widget"
+
disabled = Bool(False).tag(sync=True)
"traitlets.Bool: the disabled status of the Datepicker object"
@@ -48,7 +52,7 @@ class DatePicker(v.Layout, SepalWidget):
# create the widgets
date_picker = v.DatePicker(no_title=True, v_model=None, scrollable=True)
- date_text = v.TextField(
+ self.date_text = v.TextField(
v_model=None,
label=label,
hint="YYYY-MM-DD format",
@@ -69,7 +73,7 @@ class DatePicker(v.Layout, SepalWidget):
{
"name": "activator",
"variable": "menuData",
- "children": date_text,
+ "children": self.date_text,
}
],
)
@@ -84,8 +88,28 @@ class DatePicker(v.Layout, SepalWidget):
# call the constructor
super().__init__(**kwargs)
- jslink((date_picker, "v_model"), (date_text, "v_model"))
- jslink((date_picker, "v_model"), (self, "v_model"))
+ jslink((date_picker, "v_model"), (self.date_text, "v_model"))
+ jslink((self, "v_model"), (date_picker, "v_model"))
+
+ @observe("v_model")
+ def check_date(self, change):
+ """
+ A method to check if the value of the set v_model is a correctly formated date
+ Reset the widget and display an error if it's not the case
+ """
+
+ self.date_text.error_messages = None
+
+ # exit immediately if nothing is set
+ if change["new"] is None:
+ return
+
+ # change the error status
+ if not self.is_valid_date(change["new"]):
+ msg = self.date_text.hint
+ self.date_text.error_messages = msg
+
+ return
@observe("v_model")
def close_menu(self, change):
@@ -104,6 +128,27 @@ class DatePicker(v.Layout, SepalWidget):
return
+ @staticmethod
+ def is_valid_date(date):
+ """
+ Check if the date is provided using the date format required for the widget
+
+ Args:
+ date (str): the date to test in YYYY-MM-DD format
+
+ Return:
+ (bool): the date to test
+ """
+
+ try:
+ date = datetime.strptime(date, "%Y-%m-%d")
+ valid = True
+
+ except Exception:
+ valid = False
+
+ return valid
+
class FileInput(v.Flex, SepalWidget):
"""
|
12rambau__sepal_ui-459
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/app.py:NavDrawer.__init__"
],
"edited_modules": [
"sepal_ui/sepalwidgets/app.py:NavDrawer"
]
},
"file": "sepal_ui/sepalwidgets/app.py"
},
{
"changes": {
"added_entities": [
"sepal_ui/translator/translator.py:Translator.delete_empty"
],
"added_modules": null,
"edited_entities": [
"sepal_ui/translator/translator.py:Translator.merge_dict"
],
"edited_modules": [
"sepal_ui/translator/translator.py:Translator"
]
},
"file": "sepal_ui/translator/translator.py"
}
] |
12rambau/sepal_ui
|
a4b3091755a11ef31a3714858007a93b750b6a79
|
crowdin untranslated keys are marked as empty string
These string are interpreted as "something" by the translator leading to empty strings everywhere in the build-in component.
They should be ignored
|
diff --git a/docs/source/modules/sepal_ui.translator.Translator.rst b/docs/source/modules/sepal_ui.translator.Translator.rst
index 60fa976c..642a3ab6 100644
--- a/docs/source/modules/sepal_ui.translator.Translator.rst
+++ b/docs/source/modules/sepal_ui.translator.Translator.rst
@@ -27,6 +27,7 @@ sepal\_ui.translator.Translator
~Translator.find_target
~Translator.available_locales
~Translator.merge_dict
+ ~Translator.delete_empty
.. automethod:: sepal_ui.translator.Translator.missing_keys
@@ -38,6 +39,8 @@ sepal\_ui.translator.Translator
.. automethod:: sepal_ui.translator.Translator.merge_dict
+.. automethod:: sepal_ui.translator.Translator.delete_empty
+
.. autofunction:: sepal_ui.translator.Translator.find_target
\ No newline at end of file
diff --git a/sepal_ui/message/en/locale.json b/sepal_ui/message/en/locale.json
index 632249f8..22b77234 100644
--- a/sepal_ui/message/en/locale.json
+++ b/sepal_ui/message/en/locale.json
@@ -2,11 +2,6 @@
"test_key": "Test key",
"status": "Status: {}",
"widgets": {
- "navdrawer": {
- "code": "Source code",
- "wiki": "Wiki",
- "bug": "Bug report"
- },
"asset_select": {
"types": {
"0": "Raster",
diff --git a/sepal_ui/sepalwidgets/app.py b/sepal_ui/sepalwidgets/app.py
index b004b9ee..df1e81d8 100644
--- a/sepal_ui/sepalwidgets/app.py
+++ b/sepal_ui/sepalwidgets/app.py
@@ -255,19 +255,13 @@ class NavDrawer(v.NavigationDrawer, SepalWidget):
code_link = []
if code:
- item_code = DrawerItem(
- ms.widgets.navdrawer.code, icon="far fa-file-code", href=code
- )
+ item_code = DrawerItem("Source code", icon="far fa-file-code", href=code)
code_link.append(item_code)
if wiki:
- item_wiki = DrawerItem(
- ms.widgets.navdrawer.wiki, icon="fas fa-book-open", href=wiki
- )
+ item_wiki = DrawerItem("Wiki", icon="fas fa-book-open", href=wiki)
code_link.append(item_wiki)
if issue:
- item_bug = DrawerItem(
- ms.widgets.navdrawer.bug, icon="fas fa-bug", href=issue
- )
+ item_bug = DrawerItem("Bug report", icon="fas fa-bug", href=issue)
code_link.append(item_bug)
children = [
diff --git a/sepal_ui/translator/translator.py b/sepal_ui/translator/translator.py
index f0a39f77..f4fdec47 100644
--- a/sepal_ui/translator/translator.py
+++ b/sepal_ui/translator/translator.py
@@ -166,7 +166,8 @@ class Translator(SimpleNamespace):
Identify numbered dictionnaries embeded in the dict and transform them into lists
This function is an helper to prevent deprecation after the introduction of pontoon for translation.
- The user is now force to use keys even for numbered lists. SimpleNamespace doesn't support integer indexing so this function will transform back this "numbered" dictionnary (with integer keys) into lists.
+ The user is now force to use keys even for numbered lists. SimpleNamespace doesn't support integer indexing
+ so this function will transform back this "numbered" dictionnary (with integer keys) into lists.
Args:
d (dict): the dictionnary to sanitize
@@ -252,7 +253,8 @@ class Translator(SimpleNamespace):
"""
gather all the .json file in the provided l10n folder as 1 single json dict
- the json dict will be sanitysed and the key will be used as if they were coming from 1 single file. be careful with duplication
+ the json dict will be sanitysed and the key will be used as if they were coming from 1 single file.
+ be careful with duplication. empty string keys will be removed.
Args:
folder (pathlib.path)
@@ -264,6 +266,29 @@ class Translator(SimpleNamespace):
final_json = {}
for f in folder.glob("*.json"):
- final_json = {**final_json, **cls.sanitize(json.loads(f.read_text()))}
+ tmp_dict = cls.delete_empty(json.loads(f.read_text()))
+ final_json = {**final_json, **cls.sanitize(tmp_dict)}
return final_json
+
+ @versionadded(version="2.8.1")
+ @classmethod
+ def delete_empty(cls, d):
+ """
+ Remove empty strings ("") recursively from the dictionaries. This is to prevent untranslated strings from
+ Crowdin to be uploaded. The dictionnary must only embed dictionnaries and no lists.
+
+ Args:
+ d (dict): the dictionnary to sanitize
+
+ Return:
+ (dict): the sanitized dictionnary
+
+ """
+ for k, v in list(d.items()):
+ if isinstance(v, dict):
+ cls.delete_empty(v)
+ elif v == "":
+ del d[k]
+
+ return d
|
12rambau__sepal_ui-501
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/app.py:LocaleSelect.__init__"
],
"edited_modules": [
"sepal_ui/sepalwidgets/app.py:LocaleSelect"
]
},
"file": "sepal_ui/sepalwidgets/app.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/translator/translator.py:Translator.__init__",
"sepal_ui/translator/translator.py:Translator.search_key",
"sepal_ui/translator/translator.py:Translator.missing_keys",
"sepal_ui/translator/translator.py:Translator.available_locales"
],
"edited_modules": [
"sepal_ui/translator/translator.py:Translator"
]
},
"file": "sepal_ui/translator/translator.py"
}
] |
12rambau/sepal_ui
|
7eb3f48735e1cfeac75fecf88dd8194c8daea3d3
|
use box for the translator ?
I discovered this lib while working on the geemap drop.
I think it could be super handy for the translator keys and maybe faster. https://github.com/cdgriffith/Box
side note: we will need it anyway for the geemap drop
|
diff --git a/docs/source/modules/sepal_ui.translator.Translator.rst b/docs/source/modules/sepal_ui.translator.Translator.rst
index 642a3ab6..7f11e39f 100644
--- a/docs/source/modules/sepal_ui.translator.Translator.rst
+++ b/docs/source/modules/sepal_ui.translator.Translator.rst
@@ -2,19 +2,6 @@ sepal\_ui.translator.Translator
===============================
.. autoclass:: sepal_ui.translator.Translator
-
- .. rubric:: Attributes
-
- .. autosummary::
-
- ~Translator.default_dict
- ~Translator.target_dict
- ~Translator.default
- ~Translator.target
- ~Translator.targeted
- ~Translator.match
- ~Translator.keys
- ~Translator.folder
.. rubric:: Methods
@@ -33,7 +20,7 @@ sepal\_ui.translator.Translator
.. automethod:: sepal_ui.translator.Translator.sanitize
-.. automethod:: sepal_ui.translator.Translator.search_key
+.. autofunction:: sepal_ui.translator.Translator.search_key
.. automethod:: sepal_ui.translator.Translator.available_locales
diff --git a/sepal_ui/sepalwidgets/app.py b/sepal_ui/sepalwidgets/app.py
index 96c10461..bfd59e3d 100644
--- a/sepal_ui/sepalwidgets/app.py
+++ b/sepal_ui/sepalwidgets/app.py
@@ -602,7 +602,7 @@ class LocaleSelect(v.Menu, SepalWidget):
# extract the language information from the translator
# if not set default to english
- code = "en" if translator is None else translator.target
+ code = "en" if translator is None else translator._target
loc = self.COUNTRIES[self.COUNTRIES.code == code].squeeze()
attr = {**self.ATTR, "src": self.FLAG.format(loc.flag), "alt": loc.name}
diff --git a/sepal_ui/translator/translator.py b/sepal_ui/translator/translator.py
index f4fdec47..efa29bc9 100644
--- a/sepal_ui/translator/translator.py
+++ b/sepal_ui/translator/translator.py
@@ -1,21 +1,26 @@
import json
-from types import SimpleNamespace
from pathlib import Path
from collections import abc
-from deepdiff import DeepDiff
from configparser import ConfigParser
-from deprecated.sphinx import versionadded
+from deprecated.sphinx import versionadded, deprecated
+from box import Box
from sepal_ui import config_file
-class Translator(SimpleNamespace):
+class Translator(Box):
"""
- The translator is a SimpleNamespace of Simplenamespace. It reads 2 Json files, the first one being the source language (usually English) and the second one the target language.
+ The translator is a Python Box of boxes. It reads 2 Json files, the first one being the source language (usually English) and the second one the target language.
It will replace in the source dictionary every key that exist in both json dictionaries. Following this procedure, every message that is not translated can still be accessed in the source language.
To access the dictionary keys, instead of using [], you can simply use key name as in an object ex: translator.first_key.secondary_key.
There are no depth limits, just respect the snake_case convention when naming your keys in the .json files.
+ 5 internal keys are created upon initialization (there name cannot be used as keys in the translation message):
+ - (str) _default : the default locale of the translator
+ - (str) _targeted : the initially requested language. Use to display debug information to the user agent
+ - (str) _target : the target locale of the translator
+ - (bool) _match : if the target language match the one requested one by user, used to trigger information in appBar
+ - (str) _folder : the path to the l10n folder
Args:
json_folder (str | pathlib.Path): The folder where the dictionaries are stored
@@ -23,75 +28,60 @@ class Translator(SimpleNamespace):
default (str, optional): The language code (IETF BCP 47) of the source lang. default to "en" (it should be the same as the source dictionary)
"""
- FORBIDDEN_KEYS = [
- "default_dict",
- "target_dict",
- "in",
- "class",
- "default",
- "target",
- "match",
- ]
- "list(str): list of the forbidden keys, using one of them in a translation dict will throw an error"
-
- target_dict = {}
- "(dict): the target language dictionary"
-
- default_dict = {}
- "dict: the source language dictionary"
-
- default = None
- "str: the default locale of the translator"
-
- targeted = None
- "str: the initially requested language. Use to display debug information to the user agent"
-
- target = None
- "str: the target locale of the translator"
-
- match = None
- "bool: if the target language match the one requested one by user, used to trigger information in appBar"
-
- keys = None
- "all the keys can be acceced as attributes"
-
- folder = None
- "pathlib.Path: the path to the l10n folder"
+ _protected_keys = [
+ "find_target",
+ "search_key",
+ "sanitize",
+ "_update",
+ "missing_keys",
+ "available_locales",
+ "merge_dict",
+ "delete_empty",
+ ] + dir(Box)
+ "keys that cannot be used as var names as they are protected for methods"
def __init__(self, json_folder, target=None, default="en"):
- # init the simple namespace
- super().__init__()
+ # the name of the 5 variables that cannot be used as init keys
+ FORBIDDEN_KEYS = ["_folder", "_default", "_target", "_targeted", "_match"]
- # force cast to path
- self.folder = Path(json_folder)
+ # init the box with the folder
+ folder = Path(json_folder)
# reading the default dict
- self.default = default
- self.default_dict = self.merge_dict(self.folder / default)
+ default_dict = self.merge_dict(folder / default)
# create a dictionary in the target language
- self.targeted, target = self.find_target(self.folder, target)
- self.target = target or default
- self.target_dict = self.merge_dict(self.folder / self.target)
+ targeted, target = self.find_target(folder, target)
+ target = target or default
+ target_dict = self.merge_dict(folder / target)
# evaluate the matching of requested and obtained values
- self.match = self.targeted == self.target
+ match = targeted == target
# create the composite dictionary
- ms_dict = self._update(self.default_dict, self.target_dict)
+ ms_dict = self._update(default_dict, target_dict)
# check if forbidden keys are being used
- [self.search_key(ms_dict, k) for k in self.FORBIDDEN_KEYS]
+ # this will raise an error if any
+ [self.search_key(ms_dict, k) for k in FORBIDDEN_KEYS]
- # transform it into a json str
+ # # unpack the json as a simple namespace
ms_json = json.dumps(ms_dict)
+ ms_boxes = json.loads(ms_json, object_hook=lambda d: Box(**d, frozen_box=True))
- # unpack the json as a simple namespace
- ms = json.loads(ms_json, object_hook=lambda d: SimpleNamespace(**d))
+ private_keys = {
+ "_folder": str(folder),
+ "_default": default,
+ "_targeted": targeted,
+ "_target": target,
+ "_match": match,
+ }
- for k, v in ms.__dict__.items():
- setattr(self, k, getattr(ms, k))
+ # the final box is not frozen
+ # waiting for an answer here: https://github.com/cdgriffith/Box/issues/223
+ # it the meantime it's easy to call the translator using a frozen_box argument
+ super(Box, self).__init__(**private_keys, **ms_boxes)
@versionadded(version="2.7.0")
@staticmethod
@@ -139,8 +129,8 @@ class Translator(SimpleNamespace):
return (target, lang)
- @classmethod
- def search_key(cls, d, key):
+ @staticmethod
+ def search_key(d, key):
"""
Search a specific key in the d dictionary and raise an error if found
@@ -149,14 +139,9 @@ class Translator(SimpleNamespace):
key (str): the key to look for
"""
- for k, v in d.items():
- if isinstance(v, abc.Mapping):
- cls.search_key(v, key)
- else:
- if k == key:
- raise Exception(
- f"You cannot use the key {key} in your translation dictionary"
- )
+ if key in d:
+ msg = f"You cannot use the key {key} in your translation dictionary"
+ raise Exception(msg)
return
@@ -218,34 +203,19 @@ class Translator(SimpleNamespace):
return ms
+ @deprecated(version="2.9.0", reason="Not needed with automatic translators")
def missing_keys(self):
- """
- this function is intended for developer use only
- print the list of the missing keys in the target dictionnairie
-
- Return:
- (str): the list of missing keys
- """
-
- # find all the missing keys
- try:
- ddiff = DeepDiff(self.default_dict, self.target_dict)[
- "dictionary_item_removed"
- ]
- except Exception:
- ddiff = ["All messages are translated"]
-
- return "\n".join(ddiff)
+ pass
def available_locales(self):
"""
Return the available locales in the l10n folder
Return:
- (list): the lilst of str codes
+ (list): the list of str codes
"""
- return [f.name for f in self.folder.iterdir() if f.is_dir()]
+ return [f.name for f in Path(self._folder).glob("[!^._]*") if f.is_dir()]
@versionadded(version="2.7.0")
@classmethod
|
12rambau__sepal_ui-516
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"sepal_ui/aoi/aoi_model.py:AoiModel"
]
},
"file": "sepal_ui/aoi/aoi_model.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "sepal_ui/mapping/sepal_map.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "sepal_ui/mapping/value_inspector.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/tile.py:Tile.nest"
],
"edited_modules": [
"sepal_ui/sepalwidgets/tile.py:Tile"
]
},
"file": "sepal_ui/sepalwidgets/tile.py"
}
] |
12rambau/sepal_ui
|
9c319b0c21b8b1ba75173f3f85fd184747c398de
|
deprecate zip_dir
https://github.com/12rambau/sepal_ui/blob/a9255e7c566aac31ee7f8303e74fb7e8a3d57e5f/sepal_ui/aoi/aoi_model.py#L64
This folder is created on AOI call but is not used anymore as we are using the tmp module to create the tmp directory.
|
diff --git a/docs/source/modules/sepal_ui.aoi.AoiModel.rst b/docs/source/modules/sepal_ui.aoi.AoiModel.rst
index 0f5b8f1a..ccdcab52 100644
--- a/docs/source/modules/sepal_ui.aoi.AoiModel.rst
+++ b/docs/source/modules/sepal_ui.aoi.AoiModel.rst
@@ -12,7 +12,6 @@ sepal\_ui.aoi.AoiModel
~AoiModel.NAME
~AoiModel.ISO
~AoiModel.GADM_BASE_URL
- ~AoiModel.GADM_ZIP_DIR
~AoiModel.GAUL_ASSET
~AoiModel.ASSET_SUFFIX
~AoiModel.CUSTOM
diff --git a/sepal_ui/aoi/aoi_model.py b/sepal_ui/aoi/aoi_model.py
index ad2a72fb..40f9b4e6 100644
--- a/sepal_ui/aoi/aoi_model.py
+++ b/sepal_ui/aoi/aoi_model.py
@@ -61,11 +61,6 @@ class AoiModel(Model):
GADM_BASE_URL = "https://biogeo.ucdavis.edu/data/gadm3.6/gpkg/gadm36_{}_gpkg.zip"
"str: the base url to download gadm maps"
- GADM_ZIP_DIR = Path.home() / "tmp" / "GADM_zip"
- "pathlib.Path: the zip dir where we download the zips"
-
- GADM_ZIP_DIR.mkdir(parents=True, exist_ok=True)
-
GAUL_ASSET = "FAO/GAUL/2015/level{}"
"str: the GAUL asset name"
diff --git a/sepal_ui/mapping/sepal_map.py b/sepal_ui/mapping/sepal_map.py
index 6a518ccc..6ca115fc 100644
--- a/sepal_ui/mapping/sepal_map.py
+++ b/sepal_ui/mapping/sepal_map.py
@@ -16,7 +16,7 @@ import random
from haversine import haversine
import numpy as np
import rioxarray
-import xarray_leaflet
+import xarray_leaflet # noqa: F401
import matplotlib.pyplot as plt
from matplotlib import colors as mpc
from matplotlib import colorbar
@@ -38,11 +38,6 @@ from sepal_ui.mapping.basemaps import basemap_tiles
__all__ = ["SepalMap"]
-# call x_array leaflet at least once
-# flake8 will complain as it's a pluggin (i.e. never called)
-# We don't want to ignore testing F401
-xarray_leaflet
-
class SepalMap(ipl.Map):
"""
diff --git a/sepal_ui/mapping/value_inspector.py b/sepal_ui/mapping/value_inspector.py
index f848018f..783d68ad 100644
--- a/sepal_ui/mapping/value_inspector.py
+++ b/sepal_ui/mapping/value_inspector.py
@@ -3,7 +3,7 @@ import ee
import geopandas as gpd
from shapely import geometry as sg
import rioxarray
-import xarray_leaflet
+import xarray_leaflet # noqa: F401
from rasterio.crs import CRS
import rasterio as rio
import ipyvuetify as v
@@ -16,11 +16,6 @@ from sepal_ui.mapping.map_btn import MapBtn
from sepal_ui.frontend.styles import COMPONENTS
from sepal_ui.message import ms
-# call x_array leaflet at least once
-# flake8 will complain as it's a pluggin (i.e. never called)
-# We don't want to ignore testing F401
-xarray_leaflet
-
class ValueInspector(WidgetControl):
"""
diff --git a/sepal_ui/sepalwidgets/tile.py b/sepal_ui/sepalwidgets/tile.py
index dec40168..69a92dc0 100644
--- a/sepal_ui/sepalwidgets/tile.py
+++ b/sepal_ui/sepalwidgets/tile.py
@@ -76,7 +76,7 @@ class Tile(v.Layout, SepalWidget):
self._metadata["mount_id"] = "nested_tile"
# remove elevation
- self.elevation = False
+ self.children[0].elevation = False
# remove title
self.set_title()
|
12rambau__sepal_ui-518
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/mapping/aoi_control.py:AoiControl.__init__"
],
"edited_modules": [
"sepal_ui/mapping/aoi_control.py:AoiControl"
]
},
"file": "sepal_ui/mapping/aoi_control.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/mapping/fullscreen_control.py:FullScreenControl.__init__",
"sepal_ui/mapping/fullscreen_control.py:FullScreenControl.toggle_fullscreen"
],
"edited_modules": [
"sepal_ui/mapping/fullscreen_control.py:FullScreenControl"
]
},
"file": "sepal_ui/mapping/fullscreen_control.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/mapping/map_btn.py:MapBtn.__init__"
],
"edited_modules": [
"sepal_ui/mapping/map_btn.py:MapBtn"
]
},
"file": "sepal_ui/mapping/map_btn.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/mapping/value_inspector.py:ValueInspector.__init__"
],
"edited_modules": [
"sepal_ui/mapping/value_inspector.py:ValueInspector"
]
},
"file": "sepal_ui/mapping/value_inspector.py"
}
] |
12rambau/sepal_ui
|
698d446e33062934d49f9edb91cbe303b73e786f
|
add posibility to add text in the map_btn
The current implementation of the map_btn only authorize to use logos. It would be nice to let the opportunity to use letters as in the SEPAL main framework (3 letters only in capital)
|
diff --git a/sepal_ui/mapping/aoi_control.py b/sepal_ui/mapping/aoi_control.py
index 01a6aa48..ae143d2c 100644
--- a/sepal_ui/mapping/aoi_control.py
+++ b/sepal_ui/mapping/aoi_control.py
@@ -36,7 +36,7 @@ class AoiControl(WidgetControl):
kwargs["position"] = kwargs.pop("position", "topright")
# create a hoverable btn
- btn = MapBtn(logo="fas fa-search-location", v_on="menu.on")
+ btn = MapBtn(content="fas fa-search-location", v_on="menu.on")
slot = {"name": "activator", "variable": "menu", "children": btn}
self.aoi_list = sw.ListItemGroup(children=[], v_model="")
w_list = sw.List(
diff --git a/sepal_ui/mapping/fullscreen_control.py b/sepal_ui/mapping/fullscreen_control.py
index 5e23c1d6..2855fa72 100644
--- a/sepal_ui/mapping/fullscreen_control.py
+++ b/sepal_ui/mapping/fullscreen_control.py
@@ -43,7 +43,7 @@ class FullScreenControl(WidgetControl):
self.zoomed = fullscreen
# create a btn
- self.w_btn = MapBtn(logo=self.ICONS[self.zoomed])
+ self.w_btn = MapBtn(self.ICONS[self.zoomed])
# overwrite the widget set in the kwargs (if any)
kwargs["widget"] = self.w_btn
@@ -88,7 +88,7 @@ class FullScreenControl(WidgetControl):
self.zoomed = not self.zoomed
# change button icon
- self.w_btn.logo.children = [self.ICONS[self.zoomed]]
+ self.w_btn.children[0].children = [self.ICONS[self.zoomed]]
# zoom
self.template.send({"method": self.METHODS[self.zoomed], "args": []})
diff --git a/sepal_ui/mapping/map_btn.py b/sepal_ui/mapping/map_btn.py
index ab55e1c8..0ea13364 100644
--- a/sepal_ui/mapping/map_btn.py
+++ b/sepal_ui/mapping/map_btn.py
@@ -7,26 +7,26 @@ from sepal_ui.frontend.styles import map_btn_style
class MapBtn(v.Btn, sw.SepalWidget):
"""
Btn specifically design to be displayed on a map. It matches all the characteristics of
- the classic leaflet btn but as they are from ipyvuetify we can use them in combination with Menu to produce on-the-map. The MapBtn is responsive to theme changes.
- Tiles. It only accept icon as children as the space is very limited.
+ the classic leaflet btn but as they are from ipyvuetify we can use them in combination with Menu to produce on-the-map tiles.
+ The MapBtn is responsive to theme changes. It only accept icon or 3 letters as children as the space is very limited.
Args:
- logo (str): a fas/mdi fully qualified name
+ content (str): a fas/mdi fully qualified name or a string name. If a string name is used, only the 3 first letters will be displayed.
"""
- logo = None
- "(sw.Icon): a sw.Icon"
-
- def __init__(self, logo, **kwargs):
+ def __init__(self, content, **kwargs):
# create the icon
- self.logo = sw.Icon(small=True, children=[logo])
+ if content.startswith("mdi-") or content.startswith("fas fa-"):
+ content = sw.Icon(small=True, children=[content])
+ else:
+ content = content[: min(3, len(content))].upper()
# some parameters are overloaded to match the map requirements
kwargs["color"] = "text-color"
kwargs["outlined"] = True
kwargs["style_"] = " ".join([f"{k}: {v};" for k, v in map_btn_style.items()])
- kwargs["children"] = [self.logo]
+ kwargs["children"] = [content]
kwargs["icon"] = False
super().__init__(**kwargs)
diff --git a/sepal_ui/mapping/value_inspector.py b/sepal_ui/mapping/value_inspector.py
index ecc52e72..96508ba3 100644
--- a/sepal_ui/mapping/value_inspector.py
+++ b/sepal_ui/mapping/value_inspector.py
@@ -54,7 +54,7 @@ class ValueInspector(WidgetControl):
)
# create a clickable btn
- btn = MapBtn(logo="fas fa-crosshairs", v_on="menu.on")
+ btn = MapBtn("fas fa-crosshairs", v_on="menu.on")
slot = {"name": "activator", "variable": "menu", "children": btn}
close_btn = sw.Icon(children=["fas fa-times"], small=True)
title = sw.Html(tag="h4", children=[ms.v_inspector.title])
|
12rambau__sepal_ui-535
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/mapping/sepal_map.py:SepalMap.zoom_bounds"
],
"edited_modules": [
"sepal_ui/mapping/sepal_map.py:SepalMap"
]
},
"file": "sepal_ui/mapping/sepal_map.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/reclassify/table_view.py:EditDialog.__init__"
],
"edited_modules": [
"sepal_ui/reclassify/table_view.py:EditDialog"
]
},
"file": "sepal_ui/reclassify/table_view.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/alert.py:Banner.set_btn"
],
"edited_modules": [
"sepal_ui/sepalwidgets/alert.py:Banner"
]
},
"file": "sepal_ui/sepalwidgets/alert.py"
},
{
"changes": {
"added_entities": [
"sepal_ui/translator/translator.py:Translator.key_use"
],
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"sepal_ui/translator/translator.py:Translator"
]
},
"file": "sepal_ui/translator/translator.py"
}
] |
12rambau/sepal_ui
|
6a619361e90ab318463e2094fc9dbcbc85dd2e8f
|
create a translator function to check the use of the keys
If you are updating many time the same application you may end up removing some or all the existing keys. It complex to visually assess if all the remaining keys in the dict are used.
Maybe a parser could be interesting to check all the folder files and validate the keys that are used.
Usage will be of course for developer only
|
diff --git a/sepal_ui/mapping/sepal_map.py b/sepal_ui/mapping/sepal_map.py
index 57693e56..e2860daf 100644
--- a/sepal_ui/mapping/sepal_map.py
+++ b/sepal_ui/mapping/sepal_map.py
@@ -227,8 +227,8 @@ class SepalMap(ipl.Map):
# Center map to the centroid of the layer(s)
self.center = [(maxy - miny) / 2 + miny, (maxx - minx) / 2 + minx]
- # create the tuples for each corner
- tl, br, bl, tr = (minx, maxy), (maxx, miny), (minx, miny), (maxx, maxy)
+ # create the tuples for each corner in (lat/lng) convention
+ tl, br, bl, tr = (maxy, minx), (miny, maxx), (miny, minx), (maxy, maxx)
# find zoom level to display the biggest diagonal (in km)
lg, zoom = 40075, 1 # number of displayed km at zoom 1
diff --git a/sepal_ui/message/en/locale.json b/sepal_ui/message/en/locale.json
index 5989dee5..b689db70 100644
--- a/sepal_ui/message/en/locale.json
+++ b/sepal_ui/message/en/locale.json
@@ -37,7 +37,6 @@
"custom": "Custom",
"no_access": "It seems like you do not have access to the input asset or it does not exist.",
"wrong_type": "The type of the selected asset ({}) does not match authorized asset type ({}).",
- "hint": "Select an asset in the list or write a custom asset name. Be careful, you need to have access to this asset to use it",
"placeholder": "users/custom_user/custom_asset"
},
"load_table": {
@@ -65,20 +64,6 @@
"asset": "GEE Asset name",
"btn": "Select AOI",
"complete": "The AOI has been selected",
- "shape_drawn": "A shape has been drawn",
- "file_pattern": "aoi_{}",
- "no_selection": "No selection method has been picked up",
- "no_country": "No Country has been selected",
- "asset_already_exist": "The asset was already existing you can continue to use it. It's also available at :{}",
- "asset_created": "The asset has been created under the name : {}",
- "name_used": "The name was already in used, change it or delete the previous asset in your GEE acount",
- "no_asset": "No Asset has been provided",
- "check_if_asset": "Check carefully that your string is an assetId",
- "not_available": "This function is not yet available",
- "no_shape": "No shape has been drawn on the map",
- "shp_error": "An error occured with provided .shp file",
- "aoi_message": "click on \"selet these inputs\" to validate your AOI",
- "geojson_to_ee": "Convert your .csv file into a ee_object",
"exception" : {
"no_inputs": "Please provide fully qualified inputs before validating your AOI",
"no_asset" : "Please select an asset.",
@@ -98,7 +83,6 @@
"planet" : {
"exception" : {
"empty": "Please fill the required field(s).",
- "format" : "Please check the format of your inputs.",
"invalid" : "Invalid email or password",
"nosubs" : "Your credentials do not have any valid planet subscription."
},
@@ -143,7 +127,7 @@
"0": "New element",
"1": "Modify element"
},
- "btn": {
+ "btn": {
"save": {
"name": "save",
"tooltip": "create new class"
diff --git a/sepal_ui/reclassify/table_view.py b/sepal_ui/reclassify/table_view.py
index 0f8bf1cd..c3f8a35a 100644
--- a/sepal_ui/reclassify/table_view.py
+++ b/sepal_ui/reclassify/table_view.py
@@ -212,15 +212,24 @@ class EditDialog(v.Dialog):
self.title = v.CardTitle(children=[self.TITLES[0]])
# Action buttons
- btn_txt = ms.rec.table.edit_dialog.btn
- self.save = sw.Btn(btn_txt.save.name)
- save_tool = sw.Tooltip(self.save, btn_txt.save.tooltip, bottom=True)
+ self.save = sw.Btn(ms.rec.table.edit_dialog.btn.save.name)
+ save_tool = sw.Tooltip(
+ self.save, ms.rec.table.edit_dialog.btn.save.tooltip, bottom=True
+ )
- self.modify = sw.Btn(btn_txt.modify.name).hide() # by default modify is hidden
- modify_tool = sw.Tooltip(self.modify, btn_txt.modify.tooltip, bottom=True)
+ self.modify = sw.Btn(
+ ms.rec.table.edit_dialog.btn.modify.name
+ ).hide() # by default modify is hidden
+ modify_tool = sw.Tooltip(
+ self.modify, ms.rec.table.edit_dialog.btn.modify.tooltip, bottom=True
+ )
- self.cancel = sw.Btn(btn_txt.cancel.name, outlined=True, class_="ml-2")
- cancel_tool = sw.Tooltip(self.cancel, btn_txt.cancel.tooltip, bottom=True)
+ self.cancel = sw.Btn(
+ ms.rec.table.edit_dialog.btn.cancel.name, outlined=True, class_="ml-2"
+ )
+ cancel_tool = sw.Tooltip(
+ self.cancel, ms.rec.table.edit_dialog.btn.cancel.tooltip, bottom=True
+ )
actions = v.CardActions(children=[save_tool, modify_tool, cancel_tool])
diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py
index 6d869aaa..e143170e 100644
--- a/sepal_ui/sepalwidgets/alert.py
+++ b/sepal_ui/sepalwidgets/alert.py
@@ -380,8 +380,11 @@ class Banner(v.Snackbar, SepalWidget):
Args:
nb_banner (int): the number of banners in the queue
"""
- msg = ms.widgets.banner
- txt = msg.close if nb_banner == 0 else msg.next.format(nb_banner)
+ # do not wrap ms.widget.banner. If you do it won't be recognized by the key-checker of the Translator
+ if nb_banner == 0:
+ txt = ms.widgets.banner.close
+ else:
+ txt = ms.widgets.banner.next.format(nb_banner)
self.btn_close.children = [txt]
return
diff --git a/sepal_ui/translator/translator.py b/sepal_ui/translator/translator.py
index 5cf26320..f3a4b791 100644
--- a/sepal_ui/translator/translator.py
+++ b/sepal_ui/translator/translator.py
@@ -3,6 +3,7 @@ from collections import abc
from configparser import ConfigParser
from pathlib import Path
+import pandas as pd
from box import Box
from deprecated.sphinx import deprecated, versionadded
@@ -262,3 +263,58 @@ class Translator(Box):
del d[k]
return d
+
+ @versionadded(version="2.10.0")
+ def key_use(self, folder, name):
+ """
+ Parse all the files in the folder and check if keys are all used at least once.
+ Return the unused key names.
+
+ .. warning::
+
+ Don't forget that there are many ways of calling Translator variables
+ (getattr, save.cm.xxx in another variable etc...) SO don't forget to check
+ manually the variables suggested by this method before deleting them
+
+ Args:
+ folder (pathlib.Path): The application folder using this translator data
+ name (str): the name use by the translator in this app (usually "cm")
+
+ Return:
+ (list): the list of unused keys
+ """
+ # cannot set FORBIDDEN_KEY in the Box as it would lock another key
+ FORBIDDEN_KEYS = ["_folder", "_default", "_target", "_targeted", "_match"]
+
+ # sanitize folder
+ folder = Path(folder)
+
+ # get all the python files recursively
+ py_files = [
+ f for f in folder.glob("**/*.py") if ".ipynb_checkpoints" not in str(f)
+ ]
+
+ # get the flat version of all keys
+ keys = list(set(pd.json_normalize(self).columns) ^ set(FORBIDDEN_KEYS))
+
+ # init the unused keys list
+ unused_keys = []
+
+ for k in keys:
+
+ # by default we consider that the is never used
+ is_present = False
+
+ # read each python file and search for the pattern of the key
+ # if it's find change status of the counter and exit the search
+ for f in py_files:
+ tmp = f.read_text()
+ if f"{name}.{k}" in tmp:
+ is_present = True
+ break
+
+ # if nothing is find, the value is still False and the key can be
+ # added to the list
+ is_present or unused_keys.append(k)
+
+ return unused_keys
|
12rambau__sepal_ui-574
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/translator/translator.py:Translator.__init__",
"sepal_ui/translator/translator.py:Translator.search_key"
],
"edited_modules": [
"sepal_ui/translator/translator.py:Translator"
]
},
"file": "sepal_ui/translator/translator.py"
}
] |
12rambau/sepal_ui
|
412e02ef08df68c256f384081d2c7eaecc09428e
|
_protected_keys are not raising error when used in translator
`protected_keys` are not raising errors when used in a json translation file. It is also happening with the "`FORBIDDEN_KEYS`" when are used in nested levels.
To reproduce...
```Python
# set up the appropriate keys for each language
keys = {
"en": {
"find_target": "A key",
"test_key": "Test key",
"nested" : {
"items" : {
"_target" : "value"
},
},
"merge_dict" : "value"
},
"fr": {
"a_key": "Une clef",
"test_key": "Clef de test"
},
"fr-FR": {
"a_key": "Une clef",
"test_key": "Clef de test"
},
"es": {
"a_key": "Una llave"
},
}
# generate the tmp_dir in the test directory
tmp_dir = Path(".").parent / "data" / "messages"
tmp_dir.mkdir(exist_ok=True, parents=True)
# create the translation files
for lan, d in keys.items():
folder = tmp_dir / lan
folder.mkdir(exist_ok=True)
(folder / "locale.json").write_text(json.dumps(d, indent=2))
```
When the object is being instantiated, there's not any error to alert that the nested key "`_target`" cannot be used, nor the "`find_target`" in the first level.
```Python
translator = Translator(tmp_dir, "en")
```
|
diff --git a/sepal_ui/translator/translator.py b/sepal_ui/translator/translator.py
index 1ad14c98..ea647223 100644
--- a/sepal_ui/translator/translator.py
+++ b/sepal_ui/translator/translator.py
@@ -65,7 +65,7 @@ class Translator(Box):
# check if forbidden keys are being used
# this will raise an error if any
- [self.search_key(ms_dict, k) for k in FORBIDDEN_KEYS]
+ [self.search_key(ms_dict, k) for k in FORBIDDEN_KEYS + self._protected_keys]
# # unpack the json as a simple namespace
ms_json = json.dumps(ms_dict)
@@ -130,8 +130,7 @@ class Translator(Box):
return (target, lang)
- @staticmethod
- def search_key(d, key):
+ def search_key(self, d, key):
"""
Search a specific key in the d dictionary and raise an error if found
@@ -144,7 +143,9 @@ class Translator(Box):
msg = f"You cannot use the key {key} in your translation dictionary"
raise Exception(msg)
- return
+ for k, v in d.items():
+ if isinstance(v, dict):
+ return self.search_key(v, key)
@classmethod
def sanitize(cls, d):
|
12rambau__sepal_ui-601
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/inputs.py:DatePicker.__init__",
"sepal_ui/sepalwidgets/inputs.py:DatePicker.check_date"
],
"edited_modules": [
"sepal_ui/sepalwidgets/inputs.py:DatePicker"
]
},
"file": "sepal_ui/sepalwidgets/inputs.py"
}
] |
12rambau/sepal_ui
|
89f8d87dc4f83bfc2e96a111692ae252e470e8bc
|
Datepicker is not fully customizable
As our main `DatePicker` usage is as in its "menu" form, it is not handy to set some use cases:
- set a min_, max_ value directly (you have to `datepicker.children.....min_`...)
- set a default initial value with `v_model` since it is hardcoded from the beginning
- the `jslink` "link" will only work if the change is made from a "js" event, but not if you want to link the values since the initialization.
|
diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py
index 95fda88a..6293f828 100644
--- a/sepal_ui/sepalwidgets/inputs.py
+++ b/sepal_ui/sepalwidgets/inputs.py
@@ -6,6 +6,7 @@ import ee
import geopandas as gpd
import ipyvuetify as v
import pandas as pd
+from deprecated.sphinx import versionadded
from ipywidgets import jslink
from natsort import humansorted
from traitlets import Any, Bool, Dict, Int, List, Unicode, link, observe
@@ -29,13 +30,18 @@ __all__ = [
]
+@versionadded(
+ version="2.13.0",
+ reason="Empty v_model will be treated as empty string: :code:`v_model=''`.",
+)
class DatePicker(v.Layout, SepalWidget):
"""
Custom input widget to provide a reusable DatePicker. It allows to choose date as a string in the following format YYYY-MM-DD
Args:
label (str, optional): the label of the datepicker field
- kwargs (optional): any parameter from a v.Layout abject. If set, 'children' will be overwritten.
+ layout_kwargs (dict, optional): any parameter for the wrapper layout
+ kwargs (optional): any parameter from a v.DatePicker abject.
"""
@@ -48,13 +54,14 @@ class DatePicker(v.Layout, SepalWidget):
disabled = Bool(False).tag(sync=True)
"traitlets.Bool: the disabled status of the Datepicker object"
- def __init__(self, label="Date", **kwargs):
+ def __init__(self, label="Date", layout_kwargs={}, **kwargs):
+
+ kwargs["v_model"] = kwargs.get("v_model", "")
# create the widgets
- date_picker = v.DatePicker(no_title=True, v_model=None, scrollable=True)
+ self.date_picker = v.DatePicker(no_title=True, scrollable=True, **kwargs)
self.date_text = v.TextField(
- v_model=None,
label=label,
hint="YYYY-MM-DD format",
persistent_hint=True,
@@ -69,7 +76,7 @@ class DatePicker(v.Layout, SepalWidget):
offset_y=True,
v_model=False,
close_on_content_click=False,
- children=[date_picker],
+ children=[self.date_picker],
v_slots=[
{
"name": "activator",
@@ -80,17 +87,18 @@ class DatePicker(v.Layout, SepalWidget):
)
# set the default parameter
- kwargs["v_model"] = kwargs.pop("v_model", None)
- kwargs["row"] = kwargs.pop("row", True)
- kwargs["class_"] = kwargs.pop("class_", "pa-5")
- kwargs["align_center"] = kwargs.pop("align_center", True)
- kwargs["children"] = [v.Flex(xs10=True, children=[self.menu])]
+ layout_kwargs["row"] = layout_kwargs.get("row", True)
+ layout_kwargs["class_"] = layout_kwargs.get("class_", "pa-5")
+ layout_kwargs["align_center"] = layout_kwargs.get("align_center", True)
+ layout_kwargs["children"] = layout_kwargs.pop(
+ "children", [v.Flex(xs10=True, children=[self.menu])]
+ )
# call the constructor
- super().__init__(**kwargs)
+ super().__init__(**layout_kwargs)
- jslink((date_picker, "v_model"), (self.date_text, "v_model"))
- jslink((self, "v_model"), (date_picker, "v_model"))
+ link((self.date_picker, "v_model"), (self.date_text, "v_model"))
+ link((self.date_picker, "v_model"), (self, "v_model"))
@observe("v_model")
def check_date(self, change):
@@ -102,7 +110,7 @@ class DatePicker(v.Layout, SepalWidget):
self.date_text.error_messages = None
# exit immediately if nothing is set
- if change["new"] is None:
+ if not change["new"]:
return
# change the error status
|
12rambau__sepal_ui-608
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/reclassify/reclassify_view.py:ImportMatrixDialog.__init__",
"sepal_ui/reclassify/reclassify_view.py:SaveMatrixDialog.__init__",
"sepal_ui/reclassify/reclassify_view.py:ReclassifyView.__init__"
],
"edited_modules": [
"sepal_ui/reclassify/reclassify_view.py:ImportMatrixDialog",
"sepal_ui/reclassify/reclassify_view.py:SaveMatrixDialog",
"sepal_ui/reclassify/reclassify_view.py:ReclassifyView"
]
},
"file": "sepal_ui/reclassify/reclassify_view.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/reclassify/table_view.py:ClassTable.__init__",
"sepal_ui/reclassify/table_view.py:EditDialog.__init__",
"sepal_ui/reclassify/table_view.py:SaveDialog.__init__",
"sepal_ui/reclassify/table_view.py:TableView.__init__"
],
"edited_modules": [
"sepal_ui/reclassify/table_view.py:ClassTable",
"sepal_ui/reclassify/table_view.py:EditDialog",
"sepal_ui/reclassify/table_view.py:SaveDialog",
"sepal_ui/reclassify/table_view.py:TableView"
]
},
"file": "sepal_ui/reclassify/table_view.py"
},
{
"changes": {
"added_entities": [
"sepal_ui/sepalwidgets/btn.py:Btn._set_gliph",
"sepal_ui/sepalwidgets/btn.py:Btn._set_text"
],
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/btn.py:Btn.__init__",
"sepal_ui/sepalwidgets/btn.py:Btn.set_icon"
],
"edited_modules": [
"sepal_ui/sepalwidgets/btn.py:Btn"
]
},
"file": "sepal_ui/sepalwidgets/btn.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/inputs.py:FileInput.__init__"
],
"edited_modules": [
"sepal_ui/sepalwidgets/inputs.py:FileInput"
]
},
"file": "sepal_ui/sepalwidgets/inputs.py"
}
] |
12rambau/sepal_ui
|
2d5126f5e9521470cbeb5ad374f74046e889f771
|
create a function to set the text of the btn dynamically
icon and text should be editable dynamically
https://github.com/12rambau/sepal_ui/blob/8af255ec0d1cb3ad4dd74d021ad140fafef756f6/sepal_ui/sepalwidgets/btn.py#L38
|
diff --git a/docs/source/widgets/btn.rst b/docs/source/widgets/btn.rst
index 949d5468..91d92967 100644
--- a/docs/source/widgets/btn.rst
+++ b/docs/source/widgets/btn.rst
@@ -20,8 +20,8 @@ The default color is set to "primary".
v.theme.dark = False
btn = sw.Btn(
- text = "The One btn",
- icon = "fas fa-cogs"
+ msg = "The One btn",
+ gliph = "fas fa-cogs"
)
btn
@@ -42,8 +42,8 @@ Btn can be used to launch function on any Javascript event such as "click".
v.theme.dark = False
btn = sw.Btn(
- text = "The One btn",
- icon = "fas fa-cogs"
+ msg = "The One btn",
+ gliph = "fas fa-cogs"
)
btn.on_event('click', lambda *args: print('Hello world!'))
diff --git a/sepal_ui/reclassify/reclassify_view.py b/sepal_ui/reclassify/reclassify_view.py
index f4d6ca40..18a90455 100644
--- a/sepal_ui/reclassify/reclassify_view.py
+++ b/sepal_ui/reclassify/reclassify_view.py
@@ -33,8 +33,8 @@ class ImportMatrixDialog(v.Dialog):
# create the 3 widgets
title = v.CardTitle(children=["Load reclassification matrix"])
self.w_file = sw.FileInput(label="filename", folder=folder)
- self.load_btn = sw.Btn("Load")
- cancel = sw.Btn("Cancel", outlined=True)
+ self.load_btn = sw.Btn(msg="Load")
+ cancel = sw.Btn(msg="Cancel", outlined=True)
actions = v.CardActions(children=[cancel, self.load_btn])
# default params
@@ -81,8 +81,8 @@ class SaveMatrixDialog(v.Dialog):
# create the widgets
title = v.CardTitle(children=["Save matrix"])
self.w_file = v.TextField(label="filename", v_model=None)
- btn = sw.Btn("Save matrix")
- cancel = sw.Btn("Cancel", outlined=True)
+ btn = sw.Btn(msg="Save matrix")
+ cancel = sw.Btn(msg="Cancel", outlined=True)
actions = v.CardActions(children=[cancel, btn])
self.alert = sw.Alert(children=["Choose a name for the output"]).show()
@@ -464,7 +464,7 @@ class ReclassifyView(sw.Card):
self.btn_list = [
sw.Btn(
- "Custom",
+ msg="Custom",
_metadata={"path": "custom"},
small=True,
class_="mr-2",
@@ -472,7 +472,7 @@ class ReclassifyView(sw.Card):
)
] + [
sw.Btn(
- f"use {name}",
+ msg=f"use {name}",
_metadata={"path": path},
small=True,
class_="mr-2",
@@ -490,18 +490,20 @@ class ReclassifyView(sw.Card):
self.save_dialog = SaveMatrixDialog(folder=out_path)
self.import_dialog = ImportMatrixDialog(folder=out_path)
self.get_table = sw.Btn(
- ms.rec.rec.input.btn, "far fa-table", color="success", small=True
+ msg=ms.rec.rec.input.btn, gliph="far fa-table", color="success", small=True
)
self.import_table = sw.Btn(
- "import",
- "fas fa-download",
+ msg="import",
+ gliph="fas fa-download",
color="secondary",
small=True,
class_="ml-2 mr-2",
)
- self.save_table = sw.Btn("save", "fas fa-save", color="secondary", small=True)
+ self.save_table = sw.Btn(
+ msg="save", gliph="fas fa-save", color="secondary", small=True
+ )
self.reclassify_btn = sw.Btn(
- ms.rec.rec.btn, "fas fa-chess-board", small=True, disabled=True
+ msg=ms.rec.rec.btn, gliph="fas fa-chess-board", small=True, disabled=True
)
self.toolbar = v.Toolbar(
diff --git a/sepal_ui/reclassify/table_view.py b/sepal_ui/reclassify/table_view.py
index c3f8a35a..24ac31b5 100644
--- a/sepal_ui/reclassify/table_view.py
+++ b/sepal_ui/reclassify/table_view.py
@@ -49,19 +49,24 @@ class ClassTable(sw.DataTable):
# create the 4 CRUD btn
# and set them in the top slot of the table
self.edit_btn = sw.Btn(
- ms.rec.table.btn.edit,
- icon="fas fa-pencil-alt",
+ msg=ms.rec.table.btn.edit,
+ gliph="fas fa-pencil-alt",
class_="ml-2 mr-2",
color="secondary",
small=True,
)
self.delete_btn = sw.Btn(
- ms.rec.table.btn.delete, icon="fas fa-trash-alt", color="error", small=True
+ msg=ms.rec.table.btn.delete,
+ gliph="fas fa-trash-alt",
+ color="error",
+ small=True,
)
self.add_btn = sw.Btn(
- ms.rec.table.btn.add, icon="fas fa-plus", color="success", small=True
+ msg=ms.rec.table.btn.add, gliph="fas fa-plus", color="success", small=True
+ )
+ self.save_btn = sw.Btn(
+ msg=ms.rec.table.btn.save, gliph="far fa-save", small=True
)
- self.save_btn = sw.Btn(ms.rec.table.btn.save, icon="far fa-save", small=True)
slot = v.Toolbar(
class_="d-flex mb-6",
@@ -212,20 +217,19 @@ class EditDialog(v.Dialog):
self.title = v.CardTitle(children=[self.TITLES[0]])
# Action buttons
- self.save = sw.Btn(ms.rec.table.edit_dialog.btn.save.name)
+ self.save = sw.Btn(msg=ms.rec.table.edit_dialog.btn.save.name)
save_tool = sw.Tooltip(
self.save, ms.rec.table.edit_dialog.btn.save.tooltip, bottom=True
)
- self.modify = sw.Btn(
- ms.rec.table.edit_dialog.btn.modify.name
- ).hide() # by default modify is hidden
+ self.modify = sw.Btn(msg=ms.rec.table.edit_dialog.btn.modify.name)
+ self.modify.hide() # by default modify is hidden
modify_tool = sw.Tooltip(
self.modify, ms.rec.table.edit_dialog.btn.modify.tooltip, bottom=True
)
self.cancel = sw.Btn(
- ms.rec.table.edit_dialog.btn.cancel.name, outlined=True, class_="ml-2"
+ msg=ms.rec.table.edit_dialog.btn.cancel.name, outlined=True, class_="ml-2"
)
cancel_tool = sw.Tooltip(
self.cancel, ms.rec.table.edit_dialog.btn.cancel.tooltip, bottom=True
@@ -437,7 +441,7 @@ class SaveDialog(v.Dialog):
v_model=ms.rec.table.save_dialog.placeholder,
)
- self.save = sw.Btn(ms.rec.table.save_dialog.btn.save.name)
+ self.save = sw.Btn(msg=ms.rec.table.save_dialog.btn.save.name)
save = sw.Tooltip(
self.save,
ms.rec.table.save_dialog.btn.save.tooltip,
@@ -446,7 +450,7 @@ class SaveDialog(v.Dialog):
)
self.cancel = sw.Btn(
- ms.rec.table.save_dialog.btn.cancel.name, outlined=True, class_="ml-2"
+ msg=ms.rec.table.save_dialog.btn.cancel.name, outlined=True, class_="ml-2"
)
cancel = sw.Tooltip(
self.cancel, ms.rec.table.save_dialog.btn.cancel.tooltip, bottom=True
@@ -600,8 +604,8 @@ class TableView(sw.Card):
folder=self.class_path,
)
self.btn = sw.Btn(
- ms.rec.table.classif.btn,
- icon="far fa-table",
+ msg=ms.rec.table.classif.btn,
+ gliph="far fa-table",
color="success",
outlined=True,
)
diff --git a/sepal_ui/sepalwidgets/btn.py b/sepal_ui/sepalwidgets/btn.py
index c6437d86..137622fa 100644
--- a/sepal_ui/sepalwidgets/btn.py
+++ b/sepal_ui/sepalwidgets/btn.py
@@ -1,6 +1,9 @@
+import warnings
from pathlib import Path
import ipyvuetify as v
+from deprecated.sphinx import deprecated
+from traitlets import Unicode, observe
from sepal_ui.scripts import utils as su
from sepal_ui.sepalwidgets.sepalwidget import SepalWidget
@@ -14,27 +17,83 @@ class Btn(v.Btn, SepalWidget):
the color will be defaulted to 'primary' and can be changed afterward according to your need
Args:
+ msg (str, optional): the text to display in the btn
+ gliph (str, optional): the full name of any mdi/fa icon
text (str, optional): the text to display in the btn
icon (str, optional): the full name of any mdi/fa icon
kwargs (dict, optional): any parameters from v.Btn. if set, 'children' will be overwritten.
+
+ .. deprecated:: 2.13
+ ``text`` and ``icon`` will be replaced by ``msg`` and ``gliph`` to avoid duplicating ipyvuetify trait.
"""
v_icon = None
"v.Icon: the icon in the btn"
- def __init__(self, text="Click", icon="", **kwargs):
+ gliph = Unicode("").tag(sync=True)
+ "traitlet.Unicode: the name of the icon"
+
+ msg = Unicode("").tag(sync=True)
+ "traitlet.Unicode: the text of the btn"
+
+ def __init__(self, msg="Click", gliph="", **kwargs):
+
+ # deprecation in 2.13 of text and icon
+ # as they already exist in the ipyvuetify Btn traits (as booleans)
+ if "text" in kwargs:
+ if isinstance(kwargs["text"], str):
+ msg = kwargs.pop("text")
+ warnings.warn(
+ '"text" is deprecated, please use "msg" instead', DeprecationWarning
+ )
+ if "icon" in kwargs:
+ if isinstance(kwargs["icon"], str):
+ gliph = kwargs.pop("icon")
+ warnings.warn(
+ '"icon" is deprecated, please use "gliph" instead',
+ DeprecationWarning,
+ )
# create the default v_icon
self.v_icon = v.Icon(left=True, children=[""])
- self.set_icon(icon)
# set the default parameters
kwargs["color"] = kwargs.pop("color", "primary")
- kwargs["children"] = [self.v_icon, text]
+ kwargs["children"] = [self.v_icon, self.msg]
# call the constructor
super().__init__(**kwargs)
+ self.gliph = gliph
+ self.msg = msg
+
+ @observe("gliph")
+ def _set_gliph(self, change):
+ """
+ Set a new icon. If the icon is set to "", then it's hidden
+ """
+ new_gliph = change["new"]
+ self.v_icon.children = [new_gliph]
+
+ # hide the component to avoid the right padding
+ if not new_gliph:
+ su.hide_component(self.v_icon)
+ else:
+ su.show_component(self.v_icon)
+
+ return self
+
+ @observe("msg")
+ def _set_text(self, change):
+ """
+ Set the text of the btn
+ """
+
+ self.children = [self.v_icon, change["new"]]
+
+ return self
+
+ @deprecated(version="2.14", reason="Replace by the private _set_gliph")
def set_icon(self, icon=""):
"""
set a new icon. If the icon is set to "", then it's hidden.
@@ -45,13 +104,7 @@ class Btn(v.Btn, SepalWidget):
Return:
self
"""
- self.v_icon.children = [icon]
-
- if not icon:
- su.hide_component(self.v_icon)
- else:
- su.show_component(self.v_icon)
-
+ self.gliph = icon
return self
def toggle_loading(self):
diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py
index 5a9507ad..1bb0e850 100644
--- a/sepal_ui/sepalwidgets/inputs.py
+++ b/sepal_ui/sepalwidgets/inputs.py
@@ -256,7 +256,7 @@ class FileInput(v.Flex, SepalWidget):
"name": "activator",
"variable": "x",
"children": Btn(
- icon="fas fa-search", v_model=False, v_on="x.on", text=label
+ gliph="fas fa-search", v_model=False, v_on="x.on", msg=label
),
}
],
|
12rambau__sepal_ui-644
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/btn.py:Btn.__init__",
"sepal_ui/sepalwidgets/btn.py:Btn._set_text"
],
"edited_modules": [
"sepal_ui/sepalwidgets/btn.py:Btn"
]
},
"file": "sepal_ui/sepalwidgets/btn.py"
}
] |
12rambau/sepal_ui
|
8a8196e3c7893b7a0aebdb4910e83054f59e0374
|
sepal_ui.Btn does't work as expected
I want to create a simple Icon button, to do so:
```python
sw.Btn(icon=True, gliph ="mdi-plus")
```
Doing this, without "msg" parameter will add the default text to the button which is "click", I think is worthless having that value.
So if I want to remove the default text, I would expect doing this:
```python
sw.Btn(children = [""], icon=True, gliph ="mdi-plus")
# or
sw.Btn(msg= ""] icon=True, gliph ="mdi-plus")
```
Which leads the icon aligned to the left and not centered (as it is using a empyt string as message).
|
diff --git a/sepal_ui/sepalwidgets/btn.py b/sepal_ui/sepalwidgets/btn.py
index 137622fa..105f6160 100644
--- a/sepal_ui/sepalwidgets/btn.py
+++ b/sepal_ui/sepalwidgets/btn.py
@@ -25,6 +25,9 @@ class Btn(v.Btn, SepalWidget):
.. deprecated:: 2.13
``text`` and ``icon`` will be replaced by ``msg`` and ``gliph`` to avoid duplicating ipyvuetify trait.
+
+ .. deprecated:: 2.14
+ Btn is not using a default ``msg`` anymor`.
"""
v_icon = None
@@ -36,7 +39,7 @@ class Btn(v.Btn, SepalWidget):
msg = Unicode("").tag(sync=True)
"traitlet.Unicode: the text of the btn"
- def __init__(self, msg="Click", gliph="", **kwargs):
+ def __init__(self, msg="", gliph="", **kwargs):
# deprecation in 2.13 of text and icon
# as they already exist in the ipyvuetify Btn traits (as booleans)
@@ -55,7 +58,7 @@ class Btn(v.Btn, SepalWidget):
)
# create the default v_icon
- self.v_icon = v.Icon(left=True, children=[""])
+ self.v_icon = v.Icon(children=[""])
# set the default parameters
kwargs["color"] = kwargs.pop("color", "primary")
@@ -89,6 +92,7 @@ class Btn(v.Btn, SepalWidget):
Set the text of the btn
"""
+ self.v_icon.left = bool(change["new"])
self.children = [self.v_icon, change["new"]]
return self
|
12rambau__sepal_ui-646
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/alert.py:Alert.update_progress"
],
"edited_modules": [
"sepal_ui/sepalwidgets/alert.py:Alert"
]
},
"file": "sepal_ui/sepalwidgets/alert.py"
}
] |
12rambau/sepal_ui
|
8a8196e3c7893b7a0aebdb4910e83054f59e0374
|
allow other values for progress
Now that we are supporting tqdm it should be possible to support progress values that are not between 0 and 1. https://github.com/12rambau/sepal_ui/blob/c15a83dc6c92d076e6932afab4e4b2987585894b/sepal_ui/sepalwidgets/alert.py#L98
|
diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py
index 68e3f115..de6d4abb 100644
--- a/sepal_ui/sepalwidgets/alert.py
+++ b/sepal_ui/sepalwidgets/alert.py
@@ -94,9 +94,10 @@ class Alert(v.Alert, SepalWidget):
self.show()
# cast the progress to float
+ total = tqdm_args.get("total", 1)
progress = float(progress)
- if not (0 <= progress <= 1):
- raise ValueError(f"progress should be in [0, 1], {progress} given")
+ if not (0 <= progress <= total):
+ raise ValueError(f"progress should be in [0, {total}], {progress} given")
# Prevent adding multiple times
if self.progress_output not in self.children:
@@ -107,7 +108,7 @@ class Alert(v.Alert, SepalWidget):
"bar_format", "{l_bar}{bar}{n_fmt}/{total_fmt}"
)
tqdm_args["dynamic_ncols"] = tqdm_args.pop("dynamic_ncols", tqdm_args)
- tqdm_args["total"] = tqdm_args.pop("total", 100)
+ tqdm_args["total"] = tqdm_args.pop("total", 1)
tqdm_args["desc"] = tqdm_args.pop("desc", msg)
tqdm_args["colour"] = tqdm_args.pop("tqdm_args", getattr(color, self.type))
@@ -120,7 +121,7 @@ class Alert(v.Alert, SepalWidget):
# Initialize bar
self.progress_bar.update(0)
- self.progress_bar.update(progress * 100 - self.progress_bar.n)
+ self.progress_bar.update(progress - self.progress_bar.n)
if progress == 1:
self.progress_bar.close()
|
12rambau__sepal_ui-747
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/sepalwidget.py:SepalWidget.get_children"
],
"edited_modules": [
"sepal_ui/sepalwidgets/sepalwidget.py:SepalWidget"
]
},
"file": "sepal_ui/sepalwidgets/sepalwidget.py"
}
] |
12rambau/sepal_ui
|
a683a7665a9710acd5ca939308e18539e92014b7
|
make get_children recursively again
previous implementation used recursion to find all children within the widget that matches with the query, now it returns only first level of matching children, could we make it reclusively again?
|
diff --git a/sepal_ui/sepalwidgets/sepalwidget.py b/sepal_ui/sepalwidgets/sepalwidget.py
index 40826809..00cbe015 100644
--- a/sepal_ui/sepalwidgets/sepalwidget.py
+++ b/sepal_ui/sepalwidgets/sepalwidget.py
@@ -177,11 +177,11 @@ class SepalWidget(v.VuetifyWidget):
is_klass = isinstance(w, klass)
is_val = w.attributes.get(attr, "niet") == value if attr and value else True
- # asumption: searched element won't be nested inside one another
if is_klass and is_val:
elements.append(w)
- else:
- elements = self.get_children(w, klass, attr, value, id_, elements)
+
+ # always search for nested elements
+ elements = self.get_children(w, klass, attr, value, id_, elements)
return elements
|
12rambau__sepal_ui-758
|
[
{
"changes": {
"added_entities": [
"sepal_ui/sepalwidgets/inputs.py:DatePicker.today"
],
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"sepal_ui/sepalwidgets/inputs.py:DatePicker"
]
},
"file": "sepal_ui/sepalwidgets/inputs.py"
}
] |
12rambau/sepal_ui
|
27a18eba37bec8ef1cabfa6bcc4022164ebc4c3b
|
add a today() method for the datepicker
It's something I do a lot, setting up the datepicker to today as:
```python
from sepal_ui import sepawidgets as sw
from datetime import datetime
dp = sw.Datepicker()
# do stulff and as a fallback do
dp.v_model = datetime.today().strftime("%Y-%m-%d")
```
Instead I would love to have something like:
```python
dp.today()
```
what do you think ?
|
diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py
index 04e69553..0cb7a9bf 100644
--- a/sepal_ui/sepalwidgets/inputs.py
+++ b/sepal_ui/sepalwidgets/inputs.py
@@ -156,6 +156,12 @@ class DatePicker(v.Layout, SepalWidget):
return
+ def today(self) -> Self:
+ """Update the date to the current day."""
+ self.v_model = datetime.today().strftime("%Y-%m-%d")
+
+ return self
+
@staticmethod
def is_valid_date(date: str) -> bool:
"""
|
12rambau__sepal_ui-774
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/inputs.py:FileInput.__init__",
"sepal_ui/sepalwidgets/inputs.py:FileInput._get_items"
],
"edited_modules": [
"sepal_ui/sepalwidgets/inputs.py:FileInput"
]
},
"file": "sepal_ui/sepalwidgets/inputs.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/sepalwidget.py:SepalWidget.get_children"
],
"edited_modules": [
"sepal_ui/sepalwidgets/sepalwidget.py:SepalWidget"
]
},
"file": "sepal_ui/sepalwidgets/sepalwidget.py"
}
] |
12rambau/sepal_ui
|
2576446debe3544f3edeb208c76f671ffc0c8650
|
Restrict maximum parent level from InputFile
I have some apps where I’m interested on only search up to certain level, i.e., module_downloads, and I think that in the most of them, the user doesn’t need to go upper from sepal_user, once they start clicking, they could easily get lost over multiple folders.
what if we implement a parameter called: max_depth? We could use int values to this parameter, what do you think?
|
diff --git a/sepal_ui/sepalwidgets/inputs.py b/sepal_ui/sepalwidgets/inputs.py
index 04e69553..cd561bb5 100644
--- a/sepal_ui/sepalwidgets/inputs.py
+++ b/sepal_ui/sepalwidgets/inputs.py
@@ -205,6 +205,9 @@ class FileInput(v.Flex, SepalWidget):
clear: Optional[v.Btn] = None
"clear btn to remove everything and set back to the ini folder"
+ root: t.Unicode = t.Unicode("").tag(sync=True)
+ "the root folder from which you cannot go higher in the tree."
+
v_model: t.Unicode = t.Unicode(None, allow_none=True).tag(sync=True)
"the v_model of the input"
@@ -218,6 +221,7 @@ class FileInput(v.Flex, SepalWidget):
label: str = ms.widgets.fileinput.label,
v_model: Union[str, None] = "",
clearable: bool = False,
+ root: Union[str, Path] = "",
**kwargs,
) -> None:
"""
@@ -229,10 +233,12 @@ class FileInput(v.Flex, SepalWidget):
label: the label of the input
v_model: the default value
clearable: wether or not to make the widget clearable. default to False
+ root: the root folder from which you cannot go higher in the tree.
kwargs: any parameter from a v.Flex abject. If set, 'children' will be overwritten.
"""
self.extentions = extentions
self.folder = Path(folder)
+ self.root = str(root) if isinstance(root, Path) else root
self.selected_file = v.TextField(
readonly=True,
@@ -441,7 +447,10 @@ class FileInput(v.Flex, SepalWidget):
folder_list = humansorted(folder_list, key=lambda x: x.value)
file_list = humansorted(file_list, key=lambda x: x.value)
+ folder_list.extend(file_list)
+ # add the parent item if root is set and is not reached yet
+ # if root is not set then we always display it
parent_item = v.ListItem(
value=str(folder.parent),
children=[
@@ -458,9 +467,11 @@ class FileInput(v.Flex, SepalWidget):
),
],
)
-
- folder_list.extend(file_list)
- folder_list.insert(0, parent_item)
+ root_folder = Path(self.root)
+ if self.root == "":
+ folder_list.insert(0, parent_item)
+ elif root_folder in folder.parents:
+ folder_list.insert(0, parent_item)
return folder_list
diff --git a/sepal_ui/sepalwidgets/sepalwidget.py b/sepal_ui/sepalwidgets/sepalwidget.py
index 79428748..d9d10451 100644
--- a/sepal_ui/sepalwidgets/sepalwidget.py
+++ b/sepal_ui/sepalwidgets/sepalwidget.py
@@ -13,7 +13,7 @@ Example:
"""
import warnings
-from typing import Optional, Union
+from typing import List, Optional, Union
import ipyvuetify as v
import traitlets as t
@@ -125,7 +125,7 @@ class SepalWidget(v.VuetifyWidget):
value: str = "",
id_: str = "",
elements: Optional[list] = None,
- ) -> list:
+ ) -> List[v.VuetifyWidget]:
r"""
Recursively search for every element matching the specifications.
|
12rambau__sepal_ui-814
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/sepalwidgets/alert.py:Alert.update_progress"
],
"edited_modules": [
"sepal_ui/sepalwidgets/alert.py:Alert"
]
},
"file": "sepal_ui/sepalwidgets/alert.py"
}
] |
12rambau/sepal_ui
|
6d825ae167f96ad2e7b76b96ca07de562f74dcf0
|
avoid to force developer to set total each time
I should be able to init the progress of an Alert first and then simply update the progress.
as in:
```python
from sepal_ui import sepalwidgets as sw
alert = sw.Alert()
# init
alert.update_progress(0, "toto", total=10)
# loop
for i in range(10):
alert.update_progress(i)
```
in the current implemetnation, total need to be set in every calls
|
diff --git a/sepal_ui/sepalwidgets/alert.py b/sepal_ui/sepalwidgets/alert.py
index 19718f51..8dafab92 100644
--- a/sepal_ui/sepalwidgets/alert.py
+++ b/sepal_ui/sepalwidgets/alert.py
@@ -108,14 +108,17 @@ class Alert(v.Alert, SepalWidget):
Args:
progress: the progress status in float
msg: The message to use before the progress bar
- tqdm_args (optional): any arguments supported by a tqdm progress bar
+ tqdm_args (optional): any arguments supported by a tqdm progress bar, they will only be taken into account after a call to ``self.reset()``.
"""
# show the alert
self.show()
- # cast the progress to float
- total = tqdm_args.get("total", 1)
+ # cast the progress to float and perform sanity checks
progress = float(progress)
+ if self.progress_output not in self.children:
+ total = tqdm_args.get("total", 1)
+ else:
+ total = self.progress_bar.total
if not (0 <= progress <= total):
raise ValueError(f"progress should be in [0, {total}], {progress} given")
|
12rambau__sepal_ui-896
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"sepal_ui/planetapi/planet_model.py:PlanetModel.init_session",
"sepal_ui/planetapi/planet_model.py:PlanetModel.get_mosaics",
"sepal_ui/planetapi/planet_model.py:PlanetModel.get_quad"
],
"edited_modules": [
"sepal_ui/planetapi/planet_model.py:PlanetModel"
]
},
"file": "sepal_ui/planetapi/planet_model.py"
},
{
"changes": {
"added_entities": [
"sepal_ui/planetapi/planet_view.py:PlanetView.validate_secret_file",
"sepal_ui/planetapi/planet_view.py:PlanetView.set_initial_method"
],
"added_modules": null,
"edited_entities": [
"sepal_ui/planetapi/planet_view.py:PlanetView.__init__",
"sepal_ui/planetapi/planet_view.py:PlanetView.reset",
"sepal_ui/planetapi/planet_view.py:PlanetView._swap_inputs",
"sepal_ui/planetapi/planet_view.py:PlanetView.validate"
],
"edited_modules": [
"sepal_ui/planetapi/planet_view.py:PlanetView"
]
},
"file": "sepal_ui/planetapi/planet_view.py"
}
] |
12rambau/sepal_ui
|
b91b2a2c45b4fa80a7a0c699df978ebc46682260
|
get_mosaics from planet api fails
`get_mosaics` --and probably-- `get_quads` fails when the authentication process is done `from_login`... test has been passed because we are only testing the initialization of the `Planet` `from_key` but not to get elements from it
|
diff --git a/sepal_ui/message/en/locale.json b/sepal_ui/message/en/locale.json
index abdea912..b65a232d 100644
--- a/sepal_ui/message/en/locale.json
+++ b/sepal_ui/message/en/locale.json
@@ -85,14 +85,17 @@
"exception": {
"empty": "Please fill the required field(s).",
"invalid": "Invalid email or password",
- "nosubs": "Your credentials do not have any valid planet subscription."
+ "nosubs": "Your credentials do not have any valid planet subscription.",
+ "no_secret_file": "The credentials file does not exist, use a different login method."
},
"widget": {
"username": "Planet username",
"password": "Planet password",
"apikey": "Planet API key",
+ "store": "Remember credentials file in the session.",
"method": {
"label": "Login method",
+ "from_file": "From saved credentials",
"credentials": "Credentials",
"api_key": "Planet API key"
}
diff --git a/sepal_ui/planetapi/planet_model.py b/sepal_ui/planetapi/planet_model.py
index 7aee2ed4..c3939499 100644
--- a/sepal_ui/planetapi/planet_model.py
+++ b/sepal_ui/planetapi/planet_model.py
@@ -6,8 +6,8 @@ from typing import Dict, List, Optional, Union
import nest_asyncio
import planet.data_filter as filters
-import requests
import traitlets as t
+from deprecated.sphinx import deprecated
from planet import DataClient
from planet.auth import Auth
from planet.exceptions import NoPermission
@@ -21,7 +21,6 @@ nest_asyncio.apply()
class PlanetModel(Model):
-
SUBS_URL: str = (
"https://api.planet.com/auth/v1/experimental/public/my/subscriptions"
)
@@ -56,11 +55,18 @@ class PlanetModel(Model):
if credentials:
self.init_session(credentials)
- def init_session(self, credentials: Union[str, List[str]]) -> None:
+ @deprecated(
+ version="3.0",
+ reason="credentials member is deprecated, use self.auth._key instead",
+ )
+ def init_session(
+ self, credentials: Union[str, List[str]], write_secrets: bool = False
+ ) -> None:
"""Initialize planet client with api key or credentials. It will handle errors.
Args:
- credentials: planet API key or username and password pair of planet explorer.
+ credentials: planet API key, username and password pair or a secrets planet.json file.
+ write_secrets: either to write the credentials in the secret file or not. Defaults to True.
"""
if isinstance(credentials, str):
credentials = [credentials]
@@ -70,13 +76,21 @@ class PlanetModel(Model):
if len(credentials) == 2:
self.auth = Auth.from_login(*credentials)
+
+ # Check if the str is a path to a secret file
+ elif len(credentials) == 1 and credentials[0].endswith(".json"):
+ self.auth = Auth.from_file(credentials[0])
+
else:
self.auth = Auth.from_key(credentials[0])
- self.credentials = credentials
+ self.credentials = self.auth._key
self.session = Session(auth=self.auth)
self._is_active()
+ if self.active and write_secrets:
+ self.auth.store()
+
return
def _is_active(self) -> None:
@@ -213,10 +227,11 @@ class PlanetModel(Model):
"quad_download": true
}
"""
- url = "https://api.planet.com/basemaps/v1/mosaics?api_key={}"
- res = requests.get(url.format(self.credentials[0]))
+ mosaics_url = "https://api.planet.com/basemaps/v1/mosaics"
+ request = self.session.request("GET", mosaics_url)
+ response = asyncio.run(request)
- return res.json().get("mosaics", [])
+ return response.json().get("mosaics", [])
def get_quad(self, mosaic: dict, quad_id: str) -> dict:
"""Get a quad response for a specific mosaic and quad.
@@ -245,10 +260,13 @@ class PlanetModel(Model):
"percent_covered": 100
}
"""
- url = "https://api.planet.com/basemaps/v1/mosaics/{}/quads/{}?api_key={}"
- res = requests.get(url.format(mosaic["id"], quad_id, self.credentials[0]))
+ quads_url = "https://api.planet.com/basemaps/v1/mosaics/{}/quads/{}"
+ quads_url = quads_url.format(mosaic["id"], quad_id)
+
+ request = self.session.request("GET", quads_url)
+ response = asyncio.run(request)
- return res.json() or {}
+ return response.json() or {}
@staticmethod
def search_status(d: dict) -> List[Dict[str, bool]]:
diff --git a/sepal_ui/planetapi/planet_view.py b/sepal_ui/planetapi/planet_view.py
index 1de11832..72f3d771 100644
--- a/sepal_ui/planetapi/planet_view.py
+++ b/sepal_ui/planetapi/planet_view.py
@@ -1,5 +1,6 @@
"""The ``Card`` widget to use in application to interface with Planet."""
+from pathlib import Path
from typing import Optional
import ipyvuetify as v
@@ -12,7 +13,6 @@ from sepal_ui.scripts.decorator import loading_button
class PlanetView(sw.Layout):
-
planet_model: Optional[PlanetModel] = None
"Backend model to manipulate interface actions"
@@ -47,7 +47,7 @@ class PlanetView(sw.Layout):
):
"""Stand-alone interface to capture planet lab credentials.
- It also validate its subscription and connect to the client stored in the model.
+ It also validate its subscription and connect to the client from_file in the model.
Args:
btn (sw.Btn, optional): Button to trigger the validation process in the associated model.
@@ -67,18 +67,27 @@ class PlanetView(sw.Layout):
)
self.w_password = sw.PasswordField(label=ms.planet.widget.password)
self.w_key = sw.PasswordField(label=ms.planet.widget.apikey, v_model="").hide()
+ self.w_secret_file = sw.TextField(
+ label=ms.planet.widget.store,
+ v_model=str(Path.home() / ".planet.json"),
+ readonly=True,
+ class_="mr-2",
+ ).hide()
self.w_info_view = InfoView(model=self.planet_model)
self.w_method = v.Select(
label=ms.planet.widget.method.label,
class_="mr-2",
- v_model="credentials",
+ v_model="",
items=[
+ {"value": "from_file", "text": ms.planet.widget.method.from_file},
{"value": "credentials", "text": ms.planet.widget.method.credentials},
{"value": "api_key", "text": ms.planet.widget.method.api_key},
],
)
+ self.w_store = sw.Checkbox(label=ms.planet.widget.store, v_model=True)
+
w_validation = v.Flex(
style_="flex-grow: 0 !important;",
children=[self.btn],
@@ -87,17 +96,22 @@ class PlanetView(sw.Layout):
self.children = [
self.w_method,
sw.Layout(
+ attributes={"id": "planet_credentials"},
class_="align-center",
children=[
self.w_username,
self.w_password,
self.w_key,
+ self.w_secret_file,
],
),
+ self.w_store,
]
if not btn:
- self.children[-1].set_children(w_validation, "last")
+ self.get_children(attr="id", value="planet_credentials")[0].set_children(
+ w_validation, "last"
+ )
# Set it here to avoid displacements when using button
self.set_children(self.w_info_view, "last")
@@ -108,36 +122,82 @@ class PlanetView(sw.Layout):
self.w_method.observe(self._swap_inputs, "v_model")
self.btn.on_event("click", self.validate)
+ self.set_initial_method()
+
+ def validate_secret_file(self) -> None:
+ """Validate the secret file path."""
+ if not Path(self.w_secret_file.v_model).exists():
+ self.w_secret_file.error_messages = [ms.planet.exception.no_secret_file]
+ return False
+
+ self.w_secret_file.error_messages = []
+ return True
+
+ def set_initial_method(self) -> None:
+ """Set the initial method to connect to planet lab."""
+ self.w_method.v_model = (
+ "from_file" if self.validate_secret_file() else "credentials"
+ )
+
def reset(self) -> None:
"""Empty credentials fields and restart activation mode."""
- self.w_username.v_model = None
- self.w_password.v_model = None
- self.w_key.v_model = None
+ self.w_username.v_model = ""
+ self.w_password.v_model = ""
+ self.w_key.v_model = ""
self.planet_model.__init__()
return
def _swap_inputs(self, change: dict) -> None:
- """Swap between credentials and api key inputs."""
+ """Swap between credentials and api key inputs.
+
+ Args:
+ change.new: values of from_file, credentials, api_key
+ """
self.alert.reset()
self.reset()
- self.w_username.toggle_viz()
- self.w_password.toggle_viz()
- self.w_key.toggle_viz()
+ # small detail, but validate the file every time the method is changed
+ self.validate_secret_file()
+
+ if change["new"] == "credentials":
+ self.w_username.show()
+ self.w_password.show()
+ self.w_secret_file.hide()
+ self.w_store.show()
+ self.w_key.hide()
+
+ elif change["new"] == "api_key":
+ self.w_username.hide()
+ self.w_password.hide()
+ self.w_secret_file.hide()
+ self.w_store.show()
+ self.w_key.show()
+ else:
+ self.w_username.hide()
+ self.w_password.hide()
+ self.w_key.hide()
+ self.w_store.hide()
+ self.w_secret_file.show()
return
- @loading_button(debug=True)
+ @loading_button()
def validate(self, *args) -> None:
"""Initialize planet client and validate if is active."""
self.planet_model.__init__()
if self.w_method.v_model == "credentials":
credentials = [self.w_username.v_model, self.w_password.v_model]
+
+ elif self.w_method.v_model == "api_key":
+ credentials = self.w_key.v_model
+
else:
- credentials = [self.w_key.v_model]
+ if not self.validate_secret_file():
+ raise Exception(ms.planet.exception.no_secret_file)
+ credentials = self.w_secret_file.v_model
- self.planet_model.init_session(credentials)
+ self.planet_model.init_session(credentials, write_secrets=self.w_store.v_model)
return
|
15five__scim2-filter-parser-13
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "setup.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/scim2_filter_parser/transpilers/sql.py:Transpiler.visit_AttrPath"
],
"edited_modules": [
"src/scim2_filter_parser/transpilers/sql.py:Transpiler"
]
},
"file": "src/scim2_filter_parser/transpilers/sql.py"
}
] |
15five/scim2-filter-parser
|
3ed1858b492542d0bc9b9e9ab9547641595e28c1
|
Return NamedTuple rather than tuple.
It would be nice to return a NamedTuple instead of a tuple here:
https://github.com/15five/scim2-filter-parser/blob/7ddc216f8c3dd1cdb2152944187e8f7f5ee07be2/src/scim2_filter_parser/transpilers/sql.py#L148
This way parts of each path could be accessed by name rather than by index in the tuple.
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 12a5d4f..178f172 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,10 @@
CHANGE LOG
==========
+0.3.5
+-----
+- Update the sql.Transpiler to collect namedtuples rather than tuples for attr paths
+
0.3.4
-----
- Update tox.ini and clean up linting errors
diff --git a/setup.py b/setup.py
index bbf57bf..bd16f70 100644
--- a/setup.py
+++ b/setup.py
@@ -14,7 +14,7 @@ def long_description():
setup(
name='scim2-filter-parser',
- version='0.3.4',
+ version='0.3.5',
description='A customizable parser/transpiler for SCIM2.0 filters',
url='https://github.com/15five/scim2-filter-parser',
maintainer='Paul Logston',
diff --git a/src/scim2_filter_parser/transpilers/sql.py b/src/scim2_filter_parser/transpilers/sql.py
index 6254f1e..2107758 100644
--- a/src/scim2_filter_parser/transpilers/sql.py
+++ b/src/scim2_filter_parser/transpilers/sql.py
@@ -4,9 +4,12 @@ clause based on a SCIM filter.
"""
import ast
import string
+import collections
from .. import ast as scim2ast
+AttrPath = collections.namedtuple('AttrPath', ['attr_name', 'sub_attr', 'uri'])
+
class Transpiler(ast.NodeTransformer):
"""
@@ -145,7 +148,7 @@ class Transpiler(ast.NodeTransformer):
# Convert attr_name to another value based on map.
# Otherwise, return None.
- attr_path_tuple = (attr_name_value, sub_attr_value, uri_value)
+ attr_path_tuple = AttrPath(attr_name_value, sub_attr_value, uri_value)
self.attr_paths.append(attr_path_tuple)
return self.attr_map.get(attr_path_tuple)
|
15five__scim2-filter-parser-20
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"src/scim2_filter_parser/parser.py:SCIMParser"
]
},
"file": "src/scim2_filter_parser/parser.py"
}
] |
15five/scim2-filter-parser
|
08de23c5626556a37beced764a22a2fa7021989b
|
Issue when using multiple "or" or "and"
Hi,
I am facing an issue, where the query having two or more "and" or more than two "or" is failing.
Have a look at examples below: -
1)```"displayName co \"username\" or nickName co \"username\" or userName co \"username\""```
```"displayName co \"username\" and nickName co \"username\" and userName co \"username\""```
the two queries fails giving ,
```scim2_filter_parser.parser.SCIMParserError: Parsing error at: Token(type='OR', value='or', lineno=1, index=52)```
notice above queries are having either only "or" or "and".
2)```"displayName co \"username\" and nickName co \"username\" or userName co \"username\""```
but this query works.
|
diff --git a/src/scim2_filter_parser/parser.py b/src/scim2_filter_parser/parser.py
index 516f65d..12c693e 100644
--- a/src/scim2_filter_parser/parser.py
+++ b/src/scim2_filter_parser/parser.py
@@ -110,9 +110,8 @@ class SCIMParser(Parser):
# which takes precedence over "or"
# 3. Attribute operators
precedence = (
- ('nonassoc', OR), # noqa F821
- ('nonassoc', AND), # noqa F821
- ('nonassoc', NOT), # noqa F821
+ ('left', OR, AND), # noqa F821
+ ('right', NOT), # noqa F821
)
# FILTER = attrExp / logExp / valuePath / *1"not" "(" FILTER ")"
|
15five__scim2-filter-parser-31
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "setup.py"
},
{
"changes": {
"added_entities": [
"src/scim2_filter_parser/ast.py:AttrPath.case_insensitive",
"src/scim2_filter_parser/ast.py:AttrExpr.case_insensitive"
],
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"src/scim2_filter_parser/ast.py:AttrPath",
"src/scim2_filter_parser/ast.py:AttrExpr"
]
},
"file": "src/scim2_filter_parser/ast.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/scim2_filter_parser/transpilers/django_q_object.py:Transpiler.is_filter",
"src/scim2_filter_parser/transpilers/django_q_object.py:Transpiler.visit_AttrExpr",
"src/scim2_filter_parser/transpilers/django_q_object.py:Transpiler.visit_AttrExprValue"
],
"edited_modules": [
"src/scim2_filter_parser/transpilers/django_q_object.py:Transpiler"
]
},
"file": "src/scim2_filter_parser/transpilers/django_q_object.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/scim2_filter_parser/transpilers/sql.py:Transpiler.visit_AttrExpr",
"src/scim2_filter_parser/transpilers/sql.py:Transpiler.visit_AttrExprValue"
],
"edited_modules": [
"src/scim2_filter_parser/transpilers/sql.py:Transpiler"
]
},
"file": "src/scim2_filter_parser/transpilers/sql.py"
}
] |
15five/scim2-filter-parser
|
c794bf3e50e3cb71bdcf919feb43d11912907dd2
|
userName attribute should be case-insensitive, per the RFC
From https://github.com/15five/django-scim2/issues/76
> See https://datatracker.ietf.org/doc/html/rfc7643#section-4.1.1: (userName)
> This attribute is REQUIRED and is case insensitive.
> Currently this case-insensitive behavior is not implemented and the filter lookups are case-sensitive.
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 14f28e6..35eb5c5 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,5 +1,12 @@
CHANGE LOG
==========
+0.4.0
+-----
+- Update userName to be case insensitive. #31
+
+BREAKING CHANGE: This allows queries that did not match rows before to
+match rows now!
+
0.3.9
-----
diff --git a/setup.py b/setup.py
index fa62e03..c46c582 100644
--- a/setup.py
+++ b/setup.py
@@ -14,7 +14,7 @@ def long_description():
setup(
name='scim2-filter-parser',
- version='0.3.9',
+ version='0.4.0',
description='A customizable parser/transpiler for SCIM2.0 filters',
url='https://github.com/15five/scim2-filter-parser',
maintainer='Paul Logston',
diff --git a/src/scim2_filter_parser/ast.py b/src/scim2_filter_parser/ast.py
index b019f01..28de65e 100644
--- a/src/scim2_filter_parser/ast.py
+++ b/src/scim2_filter_parser/ast.py
@@ -95,6 +95,12 @@ class AttrPath(AST):
sub_attr : (SubAttr, type(None)) # noqa: E203
uri : (str, type(None)) # noqa: E203
+ @property
+ def case_insensitive(self):
+ # userName is always case-insensitive
+ # https://datatracker.ietf.org/doc/html/rfc7643#section-4.1.1
+ return self.attr_name == 'userName'
+
class CompValue(AST):
value : str # noqa: E203
@@ -105,6 +111,10 @@ class AttrExpr(AST):
attr_path : AttrPath # noqa: E203
comp_value : CompValue # noqa: E203
+ @property
+ def case_insensitive(self):
+ return self.attr_path.case_insensitive
+
# The following classes for visiting and rewriting the AST are taken
# from Python's ast module. It's really easy to make mistakes when
diff --git a/src/scim2_filter_parser/transpilers/django_q_object.py b/src/scim2_filter_parser/transpilers/django_q_object.py
index def4633..5ef90b2 100644
--- a/src/scim2_filter_parser/transpilers/django_q_object.py
+++ b/src/scim2_filter_parser/transpilers/django_q_object.py
@@ -139,13 +139,13 @@ class Transpiler(ast.NodeTransformer):
partial = partial.replace(".", "__")
if full and partial:
# Specific to Azure
- op, value = self.visit_AttrExprValue(node.value, node.comp_value)
+ op, value = self.visit_AttrExprValue(node)
key = partial + "__" + op
return full & Q(**{key: value})
elif full:
return full
elif partial:
- op, value = self.visit_AttrExprValue(node.value, node.comp_value)
+ op, value = self.visit_AttrExprValue(node)
key = partial + "__" + op
return Q(**{key: value})
else:
@@ -159,20 +159,20 @@ class Transpiler(ast.NodeTransformer):
return None
if "." in attr:
attr = attr.replace(".", "__")
- op, value = self.visit_AttrExprValue(node.value, node.comp_value)
+ op, value = self.visit_AttrExprValue(node)
key = attr + "__" + op
query = Q(**{key: value})
if node.value == "ne":
query = ~query
return query
- def visit_AttrExprValue(self, node_value, node_comp_value):
- op = self.lookup_op(node_value)
+ def visit_AttrExprValue(self, node):
+ op = self.lookup_op(node.value)
- if node_comp_value:
+ if node.comp_value:
# There is a comp_value, so visit node and build SQL.
# prep item_id to be a str replacement placeholder
- value = self.visit(node_comp_value)
+ value = self.visit(node.comp_value)
else:
value = None
diff --git a/src/scim2_filter_parser/transpilers/sql.py b/src/scim2_filter_parser/transpilers/sql.py
index 0c3fba4..7128edb 100644
--- a/src/scim2_filter_parser/transpilers/sql.py
+++ b/src/scim2_filter_parser/transpilers/sql.py
@@ -112,28 +112,38 @@ class Transpiler(ast.NodeTransformer):
if isinstance(node.attr_path.attr_name, scim2ast.Filter):
full, partial = self.visit_PartialAttrExpr(node.attr_path.attr_name)
if full and partial:
- value = self.visit_AttrExprValue(node.value, node.comp_value)
+ value = self.visit_AttrExprValue(node)
return f'({full} AND {partial} {value})'
elif full:
return full
elif partial:
- value = self.visit_AttrExprValue(node.value, node.comp_value)
+ value = self.visit_AttrExprValue(node)
return f'{partial} {value}'
else:
return None
else:
+ # Case-insensitivity only needs to be checked in this branch
+ # because userName is currently the only attribute that can be case
+ # insensitive and userName can not be a nested part of a complex query (eg.
+ # emails.type in emails[type eq "Primary"]...).
+ # https://datatracker.ietf.org/doc/html/rfc7643#section-4.1.1
attr = self.visit(node.attr_path)
if attr is None:
return None
- value = self.visit_AttrExprValue(node.value, node.comp_value)
+
+ value = self.visit_AttrExprValue(node)
+
+ if node.case_insensitive:
+ return f'UPPER({attr}) {value}'
+
return f'{attr} {value}'
- def visit_AttrExprValue(self, node_value, node_comp_value):
- op_sql = self.lookup_op(node_value)
+ def visit_AttrExprValue(self, node):
+ op_sql = self.lookup_op(node.value)
item_id = self.get_next_id()
- if not node_comp_value:
+ if not node.comp_value:
self.params[item_id] = None
return op_sql
@@ -142,15 +152,19 @@ class Transpiler(ast.NodeTransformer):
# prep item_id to be a str replacement placeholder
item_id_placeholder = '{' + item_id + '}'
- if 'LIKE' == op_sql:
+ if node.value.lower() in self.matching_op_by_scim_op.keys():
# Add appropriate % signs to values in LIKE clause
- prefix, suffix = self.lookup_like_matching(node_value)
- value = prefix + self.visit(node_comp_value) + suffix
+ prefix, suffix = self.lookup_like_matching(node.value)
+ value = prefix + self.visit(node.comp_value) + suffix
+
else:
- value = self.visit(node_comp_value)
+ value = self.visit(node.comp_value)
self.params[item_id] = value
+ if node.case_insensitive:
+ return f'{op_sql} UPPER({item_id_placeholder})'
+
return f'{op_sql} {item_id_placeholder}'
def visit_AttrPath(self, node):
|
20c__ctl-3
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/ctl/plugins/pypi.py:PyPIPlugin.dist_path",
"src/ctl/plugins/pypi.py:PyPIPlugin.prepare"
],
"edited_modules": [
"src/ctl/plugins/pypi.py:PyPIPluginConfig",
"src/ctl/plugins/pypi.py:PyPIPlugin"
]
},
"file": "src/ctl/plugins/pypi.py"
},
{
"changes": {
"added_entities": [
"src/ctl/plugins/release.py:ReleasePlugin.set_repository"
],
"added_modules": null,
"edited_entities": [
"src/ctl/plugins/release.py:ReleasePlugin.add_arguments",
"src/ctl/plugins/release.py:ReleasePlugin.execute",
"src/ctl/plugins/release.py:ReleasePlugin.set_target"
],
"edited_modules": [
"src/ctl/plugins/release.py:ReleasePluginConfig",
"src/ctl/plugins/release.py:ReleasePlugin"
]
},
"file": "src/ctl/plugins/release.py"
}
] |
20c/ctl
|
879af37647e61767a1ede59ffd353e4cfd27cd6f
|
PyPI plugin: `target` config attribute should be `repository`
This is so it's in line with the version plugin, which currently uses `repository` to specify the target repository
The pypi plugin currently uses `repository` to specify which PyPI repository to use, this should change to `pypi_repository` as well.
Should do this before tagging 1.0.0 since it's a config schema change
|
diff --git a/src/ctl/plugins/pypi.py b/src/ctl/plugins/pypi.py
index 5d979af..a6117af 100644
--- a/src/ctl/plugins/pypi.py
+++ b/src/ctl/plugins/pypi.py
@@ -32,7 +32,7 @@ class PyPIPluginConfig(release.ReleasePluginConfig):
config_file = confu.schema.Str(help="path to pypi config file (e.g. ~/.pypirc)")
# PyPI repository name, needs to exist in your pypi config file
- repository = confu.schema.Str(
+ pypi_repository = confu.schema.Str(
help="PyPI repository name - needs to exist " "in your pypi config file",
default="pypi",
)
@@ -55,16 +55,16 @@ class PyPIPlugin(release.ReleasePlugin):
@property
def dist_path(self):
- return os.path.join(self.target.checkout_path, "dist", "*")
+ return os.path.join(self.repository.checkout_path, "dist", "*")
def prepare(self):
super(PyPIPlugin, self).prepare()
self.shell = True
- self.repository = self.get_config("repository")
+ self.pypi_repository = self.get_config("pypi_repository")
self.pypirc_path = os.path.expanduser(self.config.get("config_file"))
self.twine_settings = Settings(
config_file=self.pypirc_path,
- repository_name=self.repository,
+ repository_name=self.pypi_repository,
sign=self.get_config("sign"),
identity=self.get_config("identity"),
sign_with=self.get_config("sign_with"),
diff --git a/src/ctl/plugins/release.py b/src/ctl/plugins/release.py
index bcfa1ce..dcae2f4 100644
--- a/src/ctl/plugins/release.py
+++ b/src/ctl/plugins/release.py
@@ -18,8 +18,8 @@ import ctl.plugins.git
class ReleasePluginConfig(confu.schema.Schema):
- target = confu.schema.Str(
- help="target for release - should be a path "
+ repository = confu.schema.Str(
+ help="repository target for release - should be a path "
"to a python package or the name of a "
"repository type plugin",
cli=False,
@@ -46,16 +46,16 @@ class ReleasePlugin(command.CommandPlugin):
"version",
nargs=1,
type=str,
- help="release version - if target is managed by git, "
+ help="release version - if repository is managed by git, "
"checkout this branch/tag",
)
group.add_argument(
- "target",
+ "repository",
nargs="?",
type=str,
- default=plugin_config.get("target"),
- help=ReleasePluginConfig().target.help,
+ default=plugin_config.get("repository"),
+ help=ReleasePluginConfig().repository.help,
)
sub = parser.add_subparsers(title="Operation", dest="op")
@@ -74,7 +74,7 @@ class ReleasePlugin(command.CommandPlugin):
return {
"group": group,
- "confu_target": op_release_parser,
+ "confu_repository": op_release_parser,
"op_release_parser": op_release_parser,
"op_validate_parser": op_validate_parser,
}
@@ -84,48 +84,48 @@ class ReleasePlugin(command.CommandPlugin):
self.prepare()
self.shell = True
- self.set_target(self.get_config("target"))
+ self.set_repository(self.get_config("repository"))
self.dry_run = kwargs.get("dry")
self.version = kwargs.get("version")[0]
- self.orig_branch = self.target.branch
+ self.orig_branch = self.repository.branch
if self.dry_run:
self.log.info("Doing dry run...")
- self.log.info("Release target: {}".format(self.target))
+ self.log.info("Release repository: {}".format(self.repository))
try:
- self.target.checkout(self.version)
+ self.repository.checkout(self.version)
op = self.get_op(kwargs.get("op"))
op(**kwargs)
finally:
- self.target.checkout(self.orig_branch)
+ self.repository.checkout(self.orig_branch)
- def set_target(self, target):
- if not target:
- raise ValueError("No target specified")
+ def set_repository(self, repository):
+ if not repository:
+ raise ValueError("No repository specified")
try:
- self.target = self.other_plugin(target)
- if not isinstance(self.target, ctl.plugins.repository.RepositoryPlugin):
+ self.repository = self.other_plugin(repository)
+ if not isinstance(self.repository, ctl.plugins.repository.RepositoryPlugin):
raise TypeError(
"The plugin with the name `{}` is not a "
"repository type plugin and cannot be used "
- "as a target".format(target)
+ "as a repository".format(repository)
)
except KeyError:
- self.target = os.path.abspath(target)
- if not os.path.exists(self.target):
+ self.repository = os.path.abspath(repository)
+ if not os.path.exists(self.repository):
raise IOError(
"Target is neither a configured repository "
"plugin nor a valid file path: "
- "{}".format(self.target)
+ "{}".format(self.repository)
)
- self.target = ctl.plugins.git.temporary_plugin(
- self.ctl, "{}__tmp_repo".format(self.plugin_name), self.target
+ self.repository = ctl.plugins.git.temporary_plugin(
+ self.ctl, "{}__tmp_repo".format(self.plugin_name), self.repository
)
- self.cwd = self.target.checkout_path
+ self.cwd = self.repository.checkout_path
@expose("ctl.{plugin_name}.release")
def release(self, **kwargs):
|
2gis__k8s-handle-120
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"k8s_handle/templating.py:Renderer._evaluate_tags"
],
"edited_modules": [
"k8s_handle/templating.py:Renderer"
]
},
"file": "k8s_handle/templating.py"
}
] |
2gis/k8s-handle
|
0ce48ecc5cd78eac5894241468a53080c3ccec64
|
skip-tags does not work
Hello,
it seems `--skip-tags` does not work. Steps to reproduce:
```
git clone git@github.com:2gis/k8s-handle-example.git
```
Edit config.yaml, add some tag
```
staging:
templates:
- template: configmap.yaml.j2
- template: deployment.yaml.j2
- template: service.yaml.j2
tags: manual
```
Render is empty:
```
$ docker run --rm -v `pwd`:/tmp -w /tmp 2gis/k8s-handle k8s-handle render -s staging --skip-tags manual
_(_)_ wWWWw _
@@@@ (_)@(_) vVVVv _ @@@@ (___) _(_)_
@@()@@ wWWWw (_)\ (___) _(_)_ @@()@@ Y (_)@(_)
@@@@ (___) `|/ Y (_)@(_) @@@@ \|/ (_)
/ Y \| \|/ /(_) \| |/ |
\ | \ |/ | / \ | / \|/ |/ \| \|/
\|// \|/// \|// \|/// \|/// \|// |// \|//
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
|
diff --git a/k8s_handle/templating.py b/k8s_handle/templating.py
index 7f2d6b7..445a09e 100644
--- a/k8s_handle/templating.py
+++ b/k8s_handle/templating.py
@@ -195,7 +195,10 @@ class Renderer:
@staticmethod
def _evaluate_tags(tags, only_tags, skip_tags):
- if only_tags is None and skip_tags is None:
- return True
+ if only_tags and tags.isdisjoint(only_tags):
+ return False
- return tags.isdisjoint(skip_tags or []) and not tags.isdisjoint(only_tags or tags)
+ if skip_tags and not tags.isdisjoint(skip_tags):
+ return False
+
+ return True
|
2gis__k8s-handle-73
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"k8s_handle/config.py:_process_variable"
],
"edited_modules": [
"k8s_handle/config.py:_process_variable"
]
},
"file": "k8s_handle/config.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"k8s_handle/filesystem.py:load_yaml"
],
"edited_modules": [
"k8s_handle/filesystem.py:load_yaml"
]
},
"file": "k8s_handle/filesystem.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"k8s_handle/templating.py:get_template_contexts"
],
"edited_modules": [
"k8s_handle/templating.py:get_template_contexts"
]
},
"file": "k8s_handle/templating.py"
}
] |
2gis/k8s-handle
|
dec5c73ec1bcd694bd45651901d68cd933721b3e
|
It is not possible to concatenate several environment variables into one value
Привет.
Столкнулся с невозможностью одновременного использования нескольких переменных окружения при объявлении переменной в config.yaml. Небольшой пример:
Мы при развертывании сервиса иногда создаем более одного деплоя, registry используем как приватные так и публичные, да еще и registry приватных у нас несколько. Так же при каждом деплое у нас выбирается образ по тэгу в git. Для того, что бы не создавать множество шаблонов деплоя, мы сделали один универсальный, в цикле которого добавляем все необходимые образы. По этому все образы объявляются в config.yaml
```yaml
common:
deployments:
service_name:
containers:
app:
image: "{{ env='CI_REGISTRY' }}/service-image:{{ env='TAG' }}"
nginx:
image: "{{ env='CI_REGISTRY' }}/custom-nginx:configmap"
```
Так вот при такой записи в случае с образом nginx все ОК, в случае с контейнером app после создания манифеста имеем "{{ env='CI_REGISTRY' }}/service-image:1.0.0". Заглянул в код и понял, что в текущей реализации не получится из нескольких переменных окружения получить нужное нам имя образа.
|
diff --git a/.dockerignore b/.dockerignore
index d3f33a2..fea1e67 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -6,5 +6,10 @@ Dockerfile*
.gitignore
.idea/
.tox/
+.travis.yml
+tox.ini
__pychache__
htmlcov/
+tests/
+*.png
+
diff --git a/k8s_handle/config.py b/k8s_handle/config.py
index acbf34f..6c2564f 100644
--- a/k8s_handle/config.py
+++ b/k8s_handle/config.py
@@ -13,7 +13,7 @@ from k8s_handle.templating import b64decode
log = logging.getLogger(__name__)
INCLUDE_RE = re.compile(r'{{\s?file\s?=\s?\'(?P<file>[^\']*)\'\s?}}')
-CUSTOM_ENV_RE = re.compile(r'^(?P<prefix>.*){{\s*env\s*=\s*\'(?P<env>[^\']*)\'\s*}}(?P<postfix>.*)$') # noqa
+CUSTOM_ENV_RE = r'{{\s*env\s*=\s*\'([^\']*)\'\s*}}'
KEY_USE_KUBECONFIG = 'use_kubeconfig'
KEY_K8S_MASTER_URI = 'k8s_master_uri'
@@ -113,19 +113,15 @@ def _process_variable(variable):
if matches:
return load_yaml(matches.groupdict().get('file'))
- matches = CUSTOM_ENV_RE.match(variable)
+ try:
+ return re.sub(CUSTOM_ENV_RE, lambda m: os.environ[m.group(1)], variable)
- if matches:
- prefix = matches.groupdict().get('prefix')
- env_var_name = matches.groupdict().get('env')
- postfix = matches.groupdict().get('postfix')
-
- if os.environ.get(env_var_name) is None and settings.GET_ENVIRON_STRICT:
- raise RuntimeError('Environment variable "{}" is not set'.format(env_var_name))
-
- return prefix + os.environ.get(env_var_name, '') + postfix
+ except KeyError as err:
+ log.debug('Environment variable "{}" is not set'.format(err.args[0]))
+ if settings.GET_ENVIRON_STRICT:
+ raise RuntimeError('Environment variable "{}" is not set'.format(err.args[0]))
- return variable
+ return re.sub(CUSTOM_ENV_RE, lambda m: os.environ.get(m.group(1), ''), variable)
def _update_single_variable(value, include_history):
diff --git a/k8s_handle/filesystem.py b/k8s_handle/filesystem.py
index 5d200eb..7993290 100644
--- a/k8s_handle/filesystem.py
+++ b/k8s_handle/filesystem.py
@@ -17,7 +17,7 @@ class InvalidYamlError(Exception):
def load_yaml(path):
try:
with open(path) as f:
- return yaml.load(f.read())
+ return yaml.safe_load(f.read())
except Exception as e:
raise InvalidYamlError("file '{}' doesn't contain valid yaml: {}".format(
path, e))
diff --git a/k8s_handle/templating.py b/k8s_handle/templating.py
index 2a5c441..7476f07 100644
--- a/k8s_handle/templating.py
+++ b/k8s_handle/templating.py
@@ -19,7 +19,7 @@ log = logging.getLogger(__name__)
def get_template_contexts(file_path):
with open(file_path) as f:
try:
- contexts = yaml.load_all(f.read())
+ contexts = yaml.safe_load_all(f.read())
except Exception as e:
raise RuntimeError('Unable to load yaml file: {}, {}'.format(file_path, e))
|
2gis__k8s-handle-84
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"k8s_handle/config.py:load_context_section"
],
"edited_modules": [
"k8s_handle/config.py:load_context_section"
]
},
"file": "k8s_handle/config.py"
}
] |
2gis/k8s-handle
|
92f764f44301bcd406d588a4db5cf0333fc1ccc2
|
Empty section passes validation
Empty section string (-s "") passes validation and causes not wrapped KeyError.
|
diff --git a/k8s_handle/config.py b/k8s_handle/config.py
index df08de4..17cdb33 100644
--- a/k8s_handle/config.py
+++ b/k8s_handle/config.py
@@ -156,6 +156,9 @@ def _update_context_recursively(context, include_history=[]):
def load_context_section(section):
+ if not section:
+ raise RuntimeError('Empty section specification is not allowed')
+
if section == settings.COMMON_SECTION_NAME:
raise RuntimeError('Section "{}" is not intended to deploy'.format(settings.COMMON_SECTION_NAME))
@@ -163,7 +166,8 @@ def load_context_section(section):
if context is None:
raise RuntimeError('Config file "{}" is empty'.format(settings.CONFIG_FILE))
- if section and section not in context:
+
+ if section not in context:
raise RuntimeError('Section "{}" not found in config file "{}"'.format(section, settings.CONFIG_FILE))
# delete all sections except common and used section
|
3YOURMIND__django-migration-linter-113
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"django_migration_linter/migration_linter.py:MigrationLinter.read_migrations_list",
"django_migration_linter/migration_linter.py:MigrationLinter._gather_migrations_git",
"django_migration_linter/migration_linter.py:MigrationLinter._gather_all_migrations"
],
"edited_modules": [
"django_migration_linter/migration_linter.py:MigrationLinter"
]
},
"file": "django_migration_linter/migration_linter.py"
}
] |
3YOURMIND/django-migration-linter
|
799957a5564e8ca1ea20d7cf643abbc21db4e40f
|
Bug: --include-migrations-from argument being ignored
In version 2.2.2, using the `--include-migration-from` argument and specifying a migration .py file will not work and `lintmigrations` will run on all migration files.
On [line 299](https://github.com/3YOURMIND/django-migration-linter/blob/799957a5564e8ca1ea20d7cf643abbc21db4e40f/django_migration_linter/migration_linter.py#L299) of `migration_linter.py` the method `is_migration_file` is being called with every line of the `migrations_file_path` file instead of the filename `migrations_file_path`
|
diff --git a/django_migration_linter/migration_linter.py b/django_migration_linter/migration_linter.py
index 31f8fea..c5ea333 100644
--- a/django_migration_linter/migration_linter.py
+++ b/django_migration_linter/migration_linter.py
@@ -289,8 +289,13 @@ class MigrationLinter(object):
@classmethod
def read_migrations_list(cls, migrations_file_path):
+ """
+ Returning an empty list is different from returning None here.
+ None: no file was specified and we should consider all migrations
+ Empty list: no migration found in the file and we should consider no migration
+ """
if not migrations_file_path:
- return []
+ return None
migrations = []
try:
@@ -300,7 +305,14 @@ class MigrationLinter(object):
app_label, name = split_migration_path(line)
migrations.append((app_label, name))
except IOError:
- logger.warning("Migrations list path not found %s", migrations_file_path)
+ logger.exception("Migrations list path not found %s", migrations_file_path)
+ raise Exception("Error while reading migrations list file")
+
+ if not migrations:
+ logger.info(
+ "No valid migration paths found in the migrations file %s",
+ migrations_file_path,
+ )
return migrations
def _gather_migrations_git(self, git_commit_id, migrations_list=None):
@@ -315,7 +327,7 @@ class MigrationLinter(object):
# Only gather lines that include added migrations
if self.is_migration_file(line):
app_label, name = split_migration_path(line)
- if not migrations_list or (app_label, name) in migrations_list:
+ if migrations_list is None or (app_label, name) in migrations_list:
migration = self.migration_loader.disk_migrations[app_label, name]
migrations.append(migration)
diff_process.wait()
@@ -334,7 +346,7 @@ class MigrationLinter(object):
migration,
) in self.migration_loader.disk_migrations.items():
if app_label not in DJANGO_APPS_WITH_MIGRATIONS: # Prune Django apps
- if not migrations_list or (app_label, name) in migrations_list:
+ if migrations_list is None or (app_label, name) in migrations_list:
yield migration
def should_ignore_migration(self, app_label, migration_name, operations=()):
|
3YOURMIND__django-migration-linter-156
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"django_migration_linter/migration_linter.py:MigrationLinter.lint_migration",
"django_migration_linter/migration_linter.py:MigrationLinter.lint_runsql"
],
"edited_modules": [
"django_migration_linter/migration_linter.py:MigrationLinter"
]
},
"file": "django_migration_linter/migration_linter.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"django_migration_linter/sql_analyser/analyser.py:analyse_sql_statements"
],
"edited_modules": [
"django_migration_linter/sql_analyser/analyser.py:analyse_sql_statements"
]
},
"file": "django_migration_linter/sql_analyser/analyser.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"django_migration_linter/sql_analyser/base.py:BaseAnalyser.__init__",
"django_migration_linter/sql_analyser/base.py:BaseAnalyser.one_line_migration_tests",
"django_migration_linter/sql_analyser/base.py:BaseAnalyser.transaction_migration_tests",
"django_migration_linter/sql_analyser/base.py:BaseAnalyser._test_sql"
],
"edited_modules": [
"django_migration_linter/sql_analyser/base.py:BaseAnalyser"
]
},
"file": "django_migration_linter/sql_analyser/base.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"django_migration_linter/sql_analyser/mysql.py:MySqlAnalyser"
]
},
"file": "django_migration_linter/sql_analyser/mysql.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"django_migration_linter/sql_analyser/postgresql.py:PostgresqlAnalyser"
]
},
"file": "django_migration_linter/sql_analyser/postgresql.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"django_migration_linter/sql_analyser/sqlite.py:SqliteAnalyser"
]
},
"file": "django_migration_linter/sql_analyser/sqlite.py"
}
] |
3YOURMIND/django-migration-linter
|
a119b4ba1fdfd27bf950e109771c6fd3e41d48dc
|
Raise backend specific deployment implications
For instance, certain operations will potentially lock a table, which can have implications during deployment (lots of operations require the table => we don't acquire the lock waiting to migrate / one we have the lock, long migration, locking the table and making production hang)
https://github.com/yandex/zero-downtime-migrations might be interesting to help out for these warnings
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 75223f0..1ee0f0b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,9 @@
* the positional argument `GIT_COMMIT_ID` becomes an optional argument with the named parameter ` --git-commit-id [GIT_COMMIT_ID]`
* the `lintmigrations` command takes now two positional arguments: `lintmigrations [app_label] [migration_name]`
+New features:
+* raise warning when create or dropping an index in a non-concurrent manner using postgresql
+
Miscellaneous:
* Add complete and working support for `toml` configuration files
* Add code coverage to the linter
diff --git a/django_migration_linter/migration_linter.py b/django_migration_linter/migration_linter.py
index 3ce96ae..c83a9ea 100644
--- a/django_migration_linter/migration_linter.py
+++ b/django_migration_linter/migration_linter.py
@@ -159,17 +159,19 @@ class MigrationLinter(object):
return
sql_statements = self.get_sql(app_label, migration_name)
- errors, ignored = analyse_sql_statements(
+ errors, ignored, warnings = analyse_sql_statements(
sql_statements,
settings.DATABASES[self.database]["ENGINE"],
self.exclude_migration_tests,
)
- err, ignored_data, warnings = self.analyse_data_migration(migration)
+ err, ignored_data, warnings_data = self.analyse_data_migration(migration)
if err:
errors += err
if ignored_data:
ignored += ignored_data
+ if warnings_data:
+ warnings += warnings_data
if self.warnings_as_errors:
errors += warnings
@@ -616,7 +618,7 @@ class MigrationLinter(object):
else:
sql_statements.append(runsql.sql)
- sql_errors, sql_ignored = analyse_sql_statements(
+ sql_errors, sql_ignored, sql_warnings = analyse_sql_statements(
sql_statements,
settings.DATABASES[self.database]["ENGINE"],
self.exclude_migration_tests,
@@ -625,6 +627,8 @@ class MigrationLinter(object):
error += sql_errors
if sql_ignored:
ignored += sql_ignored
+ if sql_warnings:
+ warning += sql_warnings
# And analysse the reverse SQL
if runsql.reversible and runsql.reverse_sql != RunSQL.noop:
@@ -644,7 +648,7 @@ class MigrationLinter(object):
else:
sql_statements.append(runsql.reverse_sql)
- sql_errors, sql_ignored = analyse_sql_statements(
+ sql_errors, sql_ignored, sql_warnings = analyse_sql_statements(
sql_statements,
settings.DATABASES[self.database]["ENGINE"],
self.exclude_migration_tests,
@@ -653,5 +657,7 @@ class MigrationLinter(object):
error += sql_errors
if sql_ignored:
ignored += sql_ignored
+ if sql_warnings:
+ warning += sql_warnings
return error, ignored, warning
diff --git a/django_migration_linter/sql_analyser/analyser.py b/django_migration_linter/sql_analyser/analyser.py
index d69f873..d98610a 100644
--- a/django_migration_linter/sql_analyser/analyser.py
+++ b/django_migration_linter/sql_analyser/analyser.py
@@ -29,4 +29,4 @@ def analyse_sql_statements(
):
sql_analyser = get_sql_analyser(database_vendor, exclude_migration_tests)
sql_analyser.analyse(sql_statements)
- return sql_analyser.errors, sql_analyser.ignored
+ return sql_analyser.errors, sql_analyser.ignored, sql_analyser.warnings
diff --git a/django_migration_linter/sql_analyser/base.py b/django_migration_linter/sql_analyser/base.py
index 4b60ebf..584ebbc 100644
--- a/django_migration_linter/sql_analyser/base.py
+++ b/django_migration_linter/sql_analyser/base.py
@@ -48,24 +48,28 @@ class BaseAnalyser(object):
or re.search("ALTER TABLE .* RENAME TO", sql),
"msg": "RENAMING tables",
"mode": "one_liner",
+ "type": "error",
},
{
"code": "NOT_NULL",
"fn": has_not_null_column,
"msg": "NOT NULL constraint on columns",
"mode": "transaction",
+ "type": "error",
},
{
"code": "DROP_COLUMN",
"fn": lambda sql, **kw: re.search("DROP COLUMN", sql),
"msg": "DROPPING columns",
"mode": "one_liner",
+ "type": "error",
},
{
"code": "DROP_TABLE",
"fn": lambda sql, **kw: sql.startswith("DROP TABLE"),
"msg": "DROPPING table",
"mode": "one_liner",
+ "type": "error",
},
{
"code": "RENAME_COLUMN",
@@ -73,6 +77,7 @@ class BaseAnalyser(object):
or re.search("ALTER TABLE .* RENAME COLUMN", sql),
"msg": "RENAMING columns",
"mode": "one_liner",
+ "type": "error",
},
{
"code": "ALTER_COLUMN",
@@ -84,12 +89,14 @@ class BaseAnalyser(object):
"You may ignore this migration.)"
),
"mode": "one_liner",
+ "type": "error",
},
{
"code": "ADD_UNIQUE",
"fn": has_add_unique,
"msg": "ADDING unique constraint",
"mode": "transaction",
+ "type": "error",
},
]
@@ -98,6 +105,7 @@ class BaseAnalyser(object):
def __init__(self, exclude_migration_tests):
self.exclude_migration_tests = exclude_migration_tests or []
self.errors = []
+ self.warnings = []
self.ignored = []
self.migration_tests = update_migration_tests(
self.base_migration_tests, self.migration_tests
@@ -113,21 +121,26 @@ class BaseAnalyser(object):
@property
def one_line_migration_tests(self):
- return [test for test in self.migration_tests if test["mode"] == "one_liner"]
+ return (test for test in self.migration_tests if test["mode"] == "one_liner")
@property
def transaction_migration_tests(self):
- return [test for test in self.migration_tests if test["mode"] == "transaction"]
+ return (test for test in self.migration_tests if test["mode"] == "transaction")
def _test_sql(self, test, sql):
if test["fn"](sql, errors=self.errors):
- err = self.build_error_dict(migration_test=test, sql_statement=sql)
if test["code"] in self.exclude_migration_tests:
- logger.debug("Testing %s -- IGNORED", sql)
- self.ignored.append(err)
+ action = "IGNORED"
+ list_to_add = self.ignored
+ elif test["type"] == "warning":
+ action = "WARNING"
+ list_to_add = self.warnings
else:
- logger.debug("Testing %s -- ERROR", sql)
- self.errors.append(err)
+ action = "ERROR"
+ list_to_add = self.errors
+ logger.debug("Testing %s -- %s", sql, action)
+ err = self.build_error_dict(migration_test=test, sql_statement=sql)
+ list_to_add.append(err)
else:
logger.debug("Testing %s -- PASSED", sql)
diff --git a/django_migration_linter/sql_analyser/mysql.py b/django_migration_linter/sql_analyser/mysql.py
index 4178c32..487a85e 100644
--- a/django_migration_linter/sql_analyser/mysql.py
+++ b/django_migration_linter/sql_analyser/mysql.py
@@ -11,6 +11,7 @@ class MySqlAnalyser(BaseAnalyser):
"ALTER TABLE .* MODIFY .* (?!NULL);?$", sql
),
"mode": "one_liner",
+ "type": "error",
}
]
diff --git a/django_migration_linter/sql_analyser/postgresql.py b/django_migration_linter/sql_analyser/postgresql.py
index 5da16c2..140aba3 100644
--- a/django_migration_linter/sql_analyser/postgresql.py
+++ b/django_migration_linter/sql_analyser/postgresql.py
@@ -1,5 +1,31 @@
+import re
+
from .base import BaseAnalyser
class PostgresqlAnalyser(BaseAnalyser):
- migration_tests = []
+ migration_tests = [
+ {
+ "code": "CREATE_INDEX",
+ "fn": lambda sql, **kw: re.search("CREATE (UNIQUE )?INDEX", sql)
+ and not re.search("INDEX CONCURRENTLY", sql),
+ "msg": "CREATE INDEX locks table",
+ "mode": "one_liner",
+ "type": "warning",
+ },
+ {
+ "code": "DROP_INDEX",
+ "fn": lambda sql, **kw: re.search("DROP INDEX", sql)
+ and not re.search("INDEX CONCURRENTLY", sql),
+ "msg": "DROP INDEX locks table",
+ "mode": "one_liner",
+ "type": "warning",
+ },
+ {
+ "code": "REINDEX",
+ "fn": lambda sql, **kw: sql.startswith("REINDEX"),
+ "msg": "REINDEX locks table",
+ "mode": "one_liner",
+ "type": "warning",
+ },
+ ]
diff --git a/django_migration_linter/sql_analyser/sqlite.py b/django_migration_linter/sql_analyser/sqlite.py
index 21503c6..9a947d1 100644
--- a/django_migration_linter/sql_analyser/sqlite.py
+++ b/django_migration_linter/sql_analyser/sqlite.py
@@ -27,6 +27,7 @@ class SqliteAnalyser(BaseAnalyser):
"fn": lambda sql, **kw: re.search("ALTER TABLE .* RENAME TO", sql)
and "__old" not in sql
and "new__" not in sql,
+ "type": "error",
},
{
"code": "DROP_TABLE",
@@ -37,6 +38,7 @@ class SqliteAnalyser(BaseAnalyser):
and not any(sql.startswith("CREATE TABLE") for sql in sql_statements),
"msg": "DROPPING table",
"mode": "transaction",
+ "type": "error",
},
{
"code": "NOT_NULL",
@@ -50,8 +52,14 @@ class SqliteAnalyser(BaseAnalyser):
for sql in sql_statements
),
"mode": "transaction",
+ "type": "error",
+ },
+ {
+ "code": "ADD_UNIQUE",
+ "fn": has_add_unique,
+ "mode": "transaction",
+ "type": "error",
},
- {"code": "ADD_UNIQUE", "fn": has_add_unique, "mode": "transaction"},
]
@staticmethod
diff --git a/docs/incompatibilities.md b/docs/incompatibilities.md
index 4f7b0ef..883a79f 100644
--- a/docs/incompatibilities.md
+++ b/docs/incompatibilities.md
@@ -39,3 +39,6 @@ You can ignore check through the `--exclude-migration-test` option and specifyin
|`RUNPYTHON_MODEL_IMPORT` | Missing apps.get_model() calls for model
|`RUNPYTHON_MODEL_VARIABLE_NAME` | The model variable name is different from the model class itself
|`RUNSQL_REVERSIBLE` | RunSQL data migration is not reversible (missing reverse SQL)
+|`CREATE_INDEX` | (Postgresql specific) Creating an index without the concurrent keyword will lock the table and may generate downtime
+|`DROP_INDEX` | (Postgresql specific) Dropping an index without the concurrent keyword will lock the table and may generate downtime
+|`REINDEX` | (Postgresql specific) Reindexing will lock the table and may generate downtime
|
3YOURMIND__django-migration-linter-186
|
[
{
"changes": {
"added_entities": [
"django_migration_linter/sql_analyser/postgresql.py:has_create_index"
],
"added_modules": [
"django_migration_linter/sql_analyser/postgresql.py:has_create_index"
],
"edited_entities": null,
"edited_modules": [
"django_migration_linter/sql_analyser/postgresql.py:PostgresqlAnalyser"
]
},
"file": "django_migration_linter/sql_analyser/postgresql.py"
}
] |
3YOURMIND/django-migration-linter
|
aef3db3e4198d06c38bc4b0874e72ed657891eea
|
Linter fails on CREATE INDEX when creating a new table
Here is an example `CreateModel` from Django:
```python
migrations.CreateModel(
name='ShipmentMetadataAlert',
fields=[
('deleted_at', models.DateTimeField(blank=True, db_index=True, null=True)),
('created_at', common.fields.CreatedField(default=django.utils.timezone.now, editable=False)),
('updated_at', common.fields.LastModifiedField(default=django.utils.timezone.now, editable=False)),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')),
('message', models.TextField(blank=True, null=True)),
('level', models.CharField(blank=True, choices=[('HIGH', 'high'), ('MEDIUM', 'medium'), ('LOW', 'low')], max_length=16, null=True)),
('type', models.CharField(blank=True, choices=[('MOBILE_DEVICE_ALERT', 'MOBILE_DEVICE_ALERT'), ('NON_ACTIVE_CARRIER', 'NON_ACTIVE_CARRIER'), ('OTHER', 'OTHER')], max_length=32, null=True)),
('subtype', models.CharField(blank=True, choices=[('DRIVER_PERMISSIONS', 'DRIVER_PERMISSIONS'), ('DRIVER_LOCATION', 'DRIVER_LOCATION'), ('OTHER', 'OTHER')], max_length=32, null=True)),
('occurred_at', models.DateTimeField(null=True)),
('clear_alert_job_id', models.UUIDField(default=None, null=True)),
('metadata', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='alerts', to='shipments.ShipmentMetadata')),
],
options={
'abstract': False,
}
)
```
Here are the SQL statements that this spits out in `sqlmigrate`:
```sql
BEGIN;
--
-- Create model ShipmentMetadataAlert
--
CREATE TABLE "shipments_shipmentmetadataalert" ("deleted_at" timestamp with time zone NULL, "created_at" timestamp with time zone NOT NULL, "updated_at" timestamp with time zone NOT NULL, "id" uuid NOT NULL PRIMARY KEY, "message" text NULL, "level" varchar(16) NULL, "type" varchar(32) NULL, "subtype" varchar(32) NULL, "occurred_at" timestamp with time zone NULL, "clear_alert_job_id" uuid NULL, "metadata_id" uuid NOT NULL);
ALTER TABLE "shipments_shipmentmetadataalert" ADD CONSTRAINT "shipments_shipmentme_metadata_id_f20850e8_fk_shipments" FOREIGN KEY ("metadata_id") REFERENCES "shipments_shipmentmetadata" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "shipments_shipmentmetadataalert_deleted_at_c9a93342" ON "shipments_shipmentmetadataalert" ("deleted_at");
CREATE INDEX "shipments_shipmentmetadataalert_metadata_id_f20850e8" ON "shipments_shipmentmetadataalert" ("metadata_id");
COMMIT;
```
This is an error from the linter as it outputs the error `CREATE INDEX locks table`. But the table is being created within the migration, it just needs to recognize that.
It seems like the `CREATE INDEX` detection should work the same way that the `ADD_UNIQUE` detection works where it detects that the create table is happening in the same migration:
https://github.com/3YOURMIND/django-migration-linter/blob/db71a9db23746f64d41d681f3fecb9b066c87338/django_migration_linter/sql_analyser/base.py#L26-L40
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d1ec8e5..15fefc0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,7 +1,8 @@
-## 4.0.0
+## 4.0.0 (unreleased)
- Drop support for Python 2.7 and 3.5
- Drop support for Django 1.11, 2.0, 2.1, 3.0
+- Fix index creation detection when table is being created in the transaction (issue #178)
## 3.0.1
diff --git a/django_migration_linter/sql_analyser/postgresql.py b/django_migration_linter/sql_analyser/postgresql.py
index 140aba3..3eb18a5 100644
--- a/django_migration_linter/sql_analyser/postgresql.py
+++ b/django_migration_linter/sql_analyser/postgresql.py
@@ -3,14 +3,32 @@ import re
from .base import BaseAnalyser
+def has_create_index(sql_statements, **kwargs):
+ regex_result = None
+ for sql in sql_statements:
+ regex_result = re.search(r"CREATE (UNIQUE )?INDEX.*ON (.*) \(", sql)
+ if re.search("INDEX CONCURRENTLY", sql):
+ regex_result = None
+ elif regex_result:
+ break
+ if not regex_result:
+ return False
+
+ concerned_table = regex_result.group(2)
+ table_is_added_in_transaction = any(
+ sql.startswith("CREATE TABLE {}".format(concerned_table))
+ for sql in sql_statements
+ )
+ return not table_is_added_in_transaction
+
+
class PostgresqlAnalyser(BaseAnalyser):
migration_tests = [
{
"code": "CREATE_INDEX",
- "fn": lambda sql, **kw: re.search("CREATE (UNIQUE )?INDEX", sql)
- and not re.search("INDEX CONCURRENTLY", sql),
+ "fn": has_create_index,
"msg": "CREATE INDEX locks table",
- "mode": "one_liner",
+ "mode": "transaction",
"type": "warning",
},
{
|
3YOURMIND__django-migration-linter-222
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"django_migration_linter/migration_linter.py:MigrationLinter.get_runpython_model_import_issues"
],
"edited_modules": [
"django_migration_linter/migration_linter.py:MigrationLinter"
]
},
"file": "django_migration_linter/migration_linter.py"
}
] |
3YOURMIND/django-migration-linter
|
3baf9487bde6ae27c3ba7623a410ab6c39bb0584
|
Linter failing when using django 'through'
### through doc
https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ManyToManyField.through
### Example code
```
def forwards_func(apps, schema_editor):
Question = apps.get_model("solution", "Question")
...
Question.many_to_may.through.objects.bulk_create(...) <- this line?
...
```
### Example Error
```
(fs_solution, 0002_my_migration)... ERR (cached)
'forwards_func': Could not find an 'apps.get_model("...", "through")' call. Importing the model directly is incorrect for data migrations.
```
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a1b5213..300fe00 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 4.1.1 (unreleased)
+
+- Fixed `RunPython` model import check when using a `through` object like `MyModel.many_to_many.through.objects.filter(...)` (issue #218)
+
## 4.1.0
- Allow configuring logging for `makemigrations` command and unify behaviour with `lintmigrations` (issue #207)
diff --git a/django_migration_linter/migration_linter.py b/django_migration_linter/migration_linter.py
index f4b1695..99e72f9 100644
--- a/django_migration_linter/migration_linter.py
+++ b/django_migration_linter/migration_linter.py
@@ -531,7 +531,7 @@ class MigrationLinter(object):
@staticmethod
def get_runpython_model_import_issues(code):
- model_object_regex = re.compile(r"[^a-zA-Z]?([a-zA-Z0-9]+?)\.objects")
+ model_object_regex = re.compile(r"[^a-zA-Z0-9._]?([a-zA-Z0-9._]+?)\.objects")
function_name = code.__name__
source_code = inspect.getsource(code)
@@ -539,6 +539,7 @@ class MigrationLinter(object):
called_models = model_object_regex.findall(source_code)
issues = []
for model in called_models:
+ model = model.split(".", 1)[0]
has_get_model_call = (
re.search(
r"{}.*= +\w+\.get_model\(".format(model),
|
3YOURMIND__django-migration-linter-258
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"django_migration_linter/sql_analyser/base.py:has_not_null_column"
],
"edited_modules": [
"django_migration_linter/sql_analyser/base.py:has_not_null_column"
]
},
"file": "django_migration_linter/sql_analyser/base.py"
}
] |
3YOURMIND/django-migration-linter
|
366d16b01a72d0baa54fef55761d846b0f05b8dd
|
Adding an index with a NOT NULL condition incorrectly triggers NOT_NULL rule
Adding an index with a `WHERE` clause including `NOT NULL` gets flagged as a `NOT NULL constraint on columns` error.
## Steps to reproduce
The follow migration operation:
```python
AddIndexConcurrently(
model_name="prediction",
index=models.Index(
condition=models.Q(
("data_deleted_at__isnull", True),
("delete_data_after__isnull", False),
),
fields=["delete_data_after"],
name="delete_data_after_idx",
),
),
```
Generates the following SQL:
```sql
CREATE INDEX CONCURRENTLY "delete_data_after_idx" ON "models_prediction" ("delete_data_after") WHERE ("data_deleted_at" IS NULL AND "delete_data_after" IS NOT NULL);
```
When linted this is flagged as an error because of the `NOT NULL`, when it ought to be a safe operation.
## Investigation
Looking at the condition used for this rule, I think it might just need to permit `CREATE INDEX` requests:
```python
re.search("(?<!DROP )NOT NULL", sql) and not sql.startswith("CREATE TABLE") and not sql.startswith("CREATE INDEX")
```
https://github.com/3YOURMIND/django-migration-linter/blob/202a6d9d5dea83528cb52fd7481a5a0565cc6f83/django_migration_linter/sql_analyser/base.py#L43
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3069d91..beafd65 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,10 +4,21 @@
Instead, the linter crashes and lets the `sqlmigrate` error raise, in order to avoid letting a problematic migration pass.
One common reason for such an error is the SQL generation which requires the database to be actually migrated in order to fetch actual constraint names from it.
The crash is a sign to double-check the migration. But if you are certain the migration is safe, you can ignore it (issue #209)
+
+Features:
+
- Fixed `RunPython` model import check when using a `through` object like `MyModel.many_to_many.through.objects.filter(...)` (issue #218)
- Mark the `IgnoreMigration` operation as `elidable=True`
+
+Bug:
+
+- Don't detect not nullable field on partial index creation (issue #250)
+
+Miscellaneous:
+
- Add support for Python 3.11
- Add support for Django 4.1
+- Add support for Django 4.2
- Drop support for Django 2.2
- Internally rename "migration tests" to "migration checks"
- Add dataclasses internally instead of custom dicts
diff --git a/django_migration_linter/sql_analyser/base.py b/django_migration_linter/sql_analyser/base.py
index 2fa0646..131652e 100644
--- a/django_migration_linter/sql_analyser/base.py
+++ b/django_migration_linter/sql_analyser/base.py
@@ -40,7 +40,8 @@ def has_not_null_column(sql_statements: list[str], **kwargs) -> bool:
ends_with_default = False
return (
any(
- re.search("(?<!DROP )NOT NULL", sql) and not sql.startswith("CREATE TABLE")
+ re.search("(?<!DROP )NOT NULL", sql)
+ and not (sql.startswith("CREATE TABLE") or sql.startswith("CREATE INDEX"))
for sql in sql_statements
)
and ends_with_default is False
|
3YOURMIND__django-migration-linter-47
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"django_migration_linter/migration_linter.py:_main"
],
"edited_modules": [
"django_migration_linter/migration_linter.py:_main"
]
},
"file": "django_migration_linter/migration_linter.py"
}
] |
3YOURMIND/django-migration-linter
|
fbf0f4419336fcb1235fa57f5575ad2593354e44
|
Add --version option
Pretty straightforward. Have a `--version` that prints the current version of the linter.
|
diff --git a/django_migration_linter/migration_linter.py b/django_migration_linter/migration_linter.py
index f9c0ab1..03c2054 100644
--- a/django_migration_linter/migration_linter.py
+++ b/django_migration_linter/migration_linter.py
@@ -20,7 +20,7 @@ from subprocess import Popen, PIPE
import sys
from .cache import Cache
-from .constants import DEFAULT_CACHE_PATH, MIGRATION_FOLDER_NAME
+from .constants import DEFAULT_CACHE_PATH, MIGRATION_FOLDER_NAME, __version__
from .migration import Migration
from .utils import is_directory, is_django_project, clean_bytes_to_str
from .sql_analyser import analyse_sql_statements
@@ -287,6 +287,9 @@ def _main():
action="store_true",
help="print more information during execution",
)
+ parser.add_argument(
+ "--version", "-V", action="version", version="%(prog)s {}".format(__version__)
+ )
parser.add_argument(
"--database",
type=str,
|
42DIGITAL__bqtools-11
|
[
{
"changes": {
"added_entities": [
"fourtytwo/bqtools/__init__.py:BQTable.__repr__"
],
"added_modules": null,
"edited_entities": [
"fourtytwo/bqtools/__init__.py:BQTable.__eq__",
"fourtytwo/bqtools/__init__.py:BQTable._set_schema",
"fourtytwo/bqtools/__init__.py:BQTable._set_data",
"fourtytwo/bqtools/__init__.py:BQTable.append"
],
"edited_modules": [
"fourtytwo/bqtools/__init__.py:BQTable"
]
},
"file": "fourtytwo/bqtools/__init__.py"
}
] |
42DIGITAL/bqtools
|
98ce0de1d976f33cf04217ef50f864f74bd5ed52
|
append data to empty table.data fails - required for schema_only
```python
>>> from fourtytwo import bqtools
>>> table = bqtools.read_bq(table_ref='project.dataset.table', schema_only=True)
>>> table.append([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/bqtools/fourtytwo/bqtools/__init__.py", line 224, in append
for index in range(len(data)):
TypeError: object of type 'NoneType' has no len()
```
File "/bqtools/fourtytwo/bqtools/\_\_init\_\_.py", line 224, in append:
```python
def append(self, rows):
append_columns = _rows_to_columns(rows, self.schema)
data = self.data
for index in range(len(data)):
data[index] += append_columns[index]
```
Probably replace range(len(data)) with range(len(self.schema))
|
diff --git a/fourtytwo/bqtools/__init__.py b/fourtytwo/bqtools/__init__.py
index 9542242..136e18c 100644
--- a/fourtytwo/bqtools/__init__.py
+++ b/fourtytwo/bqtools/__init__.py
@@ -104,14 +104,21 @@ class BQTable(object):
def __init__(self, schema=None, data=None):
if DEBUG:
logging.debug('bqtools.BQTable.__init__')
-
+
self.schema = schema if schema else []
self.data = data if data else []
- #def __repr__(self):
- # pass
+ def __repr__(self):
+ schema_shape = len(self.schema)
+ if len(self.data) > 0:
+ data_shape = (len(self.data[0]), len(self.data))
+ else:
+ data_shape = (0,)
+ return '<bqtools.BQTable(shape_schema={}, shape_data={})>'.format(schema_shape, data_shape)
def __eq__(self, other):
+ if not isinstance(other, BQTable):
+ raise TypeError('other must be of type BQTable')
return self.schema == other.schema and self.data == other.data
def __setattr__(self, name, value):
@@ -146,13 +153,18 @@ class BQTable(object):
new_schema.append(bigquery.SchemaField(**field))
if self.schema and new_schema and new_schema != self.schema:
- data = self._move_columns(new_schema)
+ # TODO Handle appends to schema
+ # if len(new_schema) > len(self.schema)
+ data = self._move_columns(schema=new_schema)
else:
data = self.data
-
- data = self._typecheck(schema=new_schema, data=data)
- object.__setattr__(self, '_schema', new_schema)
- object.__setattr__(self, '_data', data)
+
+ if data:
+ data = self._typecheck(schema=new_schema, data=data)
+ object.__setattr__(self, '_schema', new_schema)
+ object.__setattr__(self, '_data', data)
+ else:
+ object.__setattr__(self, '_schema', new_schema)
def _set_data(self, data):
if DEBUG:
@@ -160,14 +172,14 @@ class BQTable(object):
if data and isinstance(data, list):
if isinstance(data[0], dict):
- data = _rows_to_columns(data, self.schema)
- data = self._typecheck(data=data)
+ data = _rows_to_columns(rows=data, schema=self.schema)
+ data = self._typecheck(data=data)
object.__setattr__(self, '_data', data)
def _move_columns(self, schema):
if DEBUG:
logging.debug('bqtools.BQTable._move_columns()')
-
+
old_field_names = [field.name for field in self.schema]
new_field_names = [field.name for field in schema]
column_order = [old_field_names.index(name) for name in new_field_names]
@@ -219,8 +231,8 @@ class BQTable(object):
self._rename_columns(mapping=columns)
def append(self, rows):
- append_columns = _rows_to_columns(rows, self.schema)
- data = self.data
+ append_columns = _rows_to_columns(rows=rows, schema=self.schema)
+ data = self.data if self.data else [[] for n in range(len(self.schema))]
for index in range(len(data)):
data[index] += append_columns[index]
self.data = data
|
4Catalyzer__flask-resty-248
|
[
{
"changes": {
"added_entities": [
"flask_resty/compat.py:_strict_run",
"flask_resty/compat.py:schema_load",
"flask_resty/compat.py:schema_dump"
],
"added_modules": [
"flask_resty/compat.py:_strict_run",
"flask_resty/compat.py:schema_load",
"flask_resty/compat.py:schema_dump"
],
"edited_entities": null,
"edited_modules": null
},
"file": "flask_resty/compat.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"flask_resty/fields.py:RelatedItem._deserialize"
],
"edited_modules": [
"flask_resty/fields.py:RelatedItem"
]
},
"file": "flask_resty/fields.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"flask_resty/view.py:ApiView.serialize",
"flask_resty/view.py:ApiView.deserialize",
"flask_resty/view.py:ApiView.request_args",
"flask_resty/view.py:ApiView.deserialize_args"
],
"edited_modules": [
"flask_resty/view.py:ApiView"
]
},
"file": "flask_resty/view.py"
}
] |
4Catalyzer/flask-resty
|
ac43163453fab1b23434d29f71a3c1b34b251c0a
|
Support Marshmallow 3
[From here](https://marshmallow.readthedocs.io/en/latest/upgrading.html#schemas-are-always-strict):
> Schema().load and Schema().dump don’t return a (data, errors) tuple any more. Only data is returned.
|
diff --git a/.travis.yml b/.travis.yml
index 708e4a9..00ffb59 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,16 +4,21 @@ services:
- postgresql
matrix:
include:
- - { python: "2.7", env: "TOXENV=py-full DATABASE_URL=postgres://localhost/travis_ci_test" }
- - { python: "3.5", env: "TOXENV=py-full DATABASE_URL=postgres://localhost/travis_ci_test" }
- - { python: "3.6", env: "TOXENV=py-full DATABASE_URL=postgres://localhost/travis_ci_test" }
- - { python: "3.7", env: "TOXENV=py-full DATABASE_URL=postgres://localhost/travis_ci_test" }
+ - { python: "2.7", env: "TOXENV=py-full-marshmallow2 DATABASE_URL=postgres://localhost/travis_ci_test" }
+ - { python: "3.5", env: "TOXENV=py-full-marshmallow2 DATABASE_URL=postgres://localhost/travis_ci_test" }
+ - { python: "3.6", env: "TOXENV=py-full-marshmallow2 DATABASE_URL=postgres://localhost/travis_ci_test" }
+ - { python: "3.7", env: "TOXENV=py-full-marshmallow2 DATABASE_URL=postgres://localhost/travis_ci_test" }
- - { python: "2.7", env: "TOXENV=py-base" }
- - { python: "3.6", env: "TOXENV=py-base" }
+ - { python: "2.7", env: "TOXENV=py-base-marshmallow2" }
+ - { python: "3.6", env: "TOXENV=py-base-marshmallow2" }
- - { python: "pypy2.7-6.0", env: "TOXENV=py-full" }
- - { python: "pypy3.5-6.0", env: "TOXENV=py-full" }
+ - { python: "2.7", env: "TOXENV=py-full-marshmallow3" }
+ - { python: "3.6", env: "TOXENV=py-full-marshmallow3" }
+ - { python: "2.7", env: "TOXENV=py-base-marshmallow3" }
+ - { python: "3.6", env: "TOXENV=py-base-marshmallow3" }
+
+ - { python: "pypy2.7-6.0", env: "TOXENV=py-full-marshmallow2" }
+ - { python: "pypy3.5-6.0", env: "TOXENV=py-full-marshmallow2" }
cache:
directories:
diff --git a/README.md b/README.md
index 91e22ef..3da8ccd 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Flask-RESTy [![Travis][build-badge]][build] [![PyPI][pypi-badge]][pypi]
+# Flask-RESTy [![Travis][build-badge]][build] [![PyPI][pypi-badge]][pypi] [![marshmallow 2/3 compatible][marshmallow-badge]][marshmallow-upgrading]
Building blocks for REST APIs for [Flask](http://flask.pocoo.org/).
[![Codecov][codecov-badge]][codecov]
@@ -79,3 +79,6 @@ class WidgetSchema(TableSchema):
[codecov-badge]: https://img.shields.io/codecov/c/github/4Catalyzer/flask-resty/master.svg
[codecov]: https://codecov.io/gh/4Catalyzer/flask-resty
+
+[marshmallow-badge]: https://badgen.net/badge/marshmallow/2,3?list=1
+[marshmallow-upgrading]: https://marshmallow.readthedocs.io/en/latest/upgrading.html
diff --git a/flask_resty/compat.py b/flask_resty/compat.py
index 76a767c..4f86e88 100644
--- a/flask_resty/compat.py
+++ b/flask_resty/compat.py
@@ -1,8 +1,11 @@
import sys
+import marshmallow
+
# -----------------------------------------------------------------------------
PY2 = int(sys.version_info[0]) == 2
+MA2 = int(marshmallow.__version__[0]) == 2
# -----------------------------------------------------------------------------
@@ -10,3 +13,23 @@ if PY2:
basestring = basestring # noqa: F821
else:
basestring = (str, bytes)
+
+
+def _strict_run(method, obj_or_data, **kwargs):
+ result = method(obj_or_data, **kwargs)
+ if MA2: # Make marshmallow 2 schemas behave like marshmallow 3
+ data, errors = result
+ if errors:
+ raise marshmallow.ValidationError(errors, data=data)
+ else:
+ data = result
+
+ return data
+
+
+def schema_load(schema, in_data, **kwargs):
+ return _strict_run(schema.load, in_data, **kwargs)
+
+
+def schema_dump(schema, obj, **kwargs):
+ return _strict_run(schema.dump, obj, **kwargs)
diff --git a/flask_resty/fields.py b/flask_resty/fields.py
index 1c2f370..e1ee7f2 100644
--- a/flask_resty/fields.py
+++ b/flask_resty/fields.py
@@ -1,19 +1,18 @@
-from marshmallow import fields, ValidationError
+from marshmallow import fields
import marshmallow.utils
+from .compat import schema_load
+
# -----------------------------------------------------------------------------
class RelatedItem(fields.Nested):
- def _deserialize(self, value, attr, data):
+ def _deserialize(self, value, *args, **kwargs):
if self.many and not marshmallow.utils.is_collection(value):
self.fail('type', input=value, type=value.__class__.__name__)
# Do partial load of related item, as we only need the id.
- data, errors = self.schema.load(value, partial=True)
- if errors:
- raise ValidationError(errors, data=data)
- return data
+ return schema_load(self.schema, value, partial=True)
def _validate_missing(self, value):
# Do not display detailed error data on required fields in nested
diff --git a/flask_resty/view.py b/flask_resty/view.py
index fc6043b..a263919 100644
--- a/flask_resty/view.py
+++ b/flask_resty/view.py
@@ -2,7 +2,7 @@ import itertools
import flask
from flask.views import MethodView
-from marshmallow import fields
+from marshmallow import fields, ValidationError
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Load
from sqlalchemy.orm.exc import NoResultFound
@@ -11,6 +11,7 @@ from werkzeug.exceptions import NotFound
from . import meta
from .authentication import NoOpAuthentication
from .authorization import NoOpAuthorization
+from .compat import MA2, schema_dump, schema_load
from .decorators import request_cached_property
from .exceptions import ApiError
from .spec import ApiViewDeclaration, ModelViewDeclaration
@@ -36,7 +37,7 @@ class ApiView(MethodView):
return super(ApiView, self).dispatch_request(*args, **kwargs)
def serialize(self, item, **kwargs):
- return self.serializer.dump(item, **kwargs).data
+ return schema_dump(self.serializer, item, **kwargs)
@settable_property
def serializer(self):
@@ -111,11 +112,12 @@ class ApiView(MethodView):
return data_raw
def deserialize(self, data_raw, expected_id=None, **kwargs):
- data, errors = self.deserializer.load(data_raw, **kwargs)
- if errors:
+ try:
+ data = schema_load(self.deserializer, data_raw, **kwargs)
+ except ValidationError as e:
raise ApiError(422, *(
self.format_validation_error(error)
- for error in iter_validation_errors(errors)
+ for error in iter_validation_errors(e.messages)
))
self.validate_request_id(data, expected_id)
@@ -170,8 +172,11 @@ class ApiView(MethodView):
for field_name, field in self.args_schema.fields.items():
if field_name in args:
args_key = field_name
- elif field.load_from and field.load_from in args:
+ elif MA2 and field.load_from and field.load_from in args:
args_key = field.load_from
+ elif not MA2 and field.data_key and field.data_key in args:
+ args_key = field.data_key
+ field_name = field.data_key
else:
continue
@@ -187,11 +192,12 @@ class ApiView(MethodView):
return isinstance(field, fields.List)
def deserialize_args(self, data_raw, **kwargs):
- data, errors = self.args_schema.load(data_raw, **kwargs)
- if errors:
+ try:
+ data = schema_load(self.args_schema, data_raw, **kwargs)
+ except ValidationError as e:
raise ApiError(422, *(
self.format_parameter_validation_error(message, parameter)
- for parameter, messages in errors.items()
+ for parameter, messages in e.messages.items()
for message in messages
))
diff --git a/tox.ini b/tox.ini
index 2a92706..8f5f3b3 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,9 +1,12 @@
[tox]
-envlist = py{27,35,37}-{base,full}
+envlist = py{27,35,37}-{base,full}-marshmallow{2,3}
[testenv]
passenv = DATABASE_URL
usedevelop = True
+deps =
+ marshmallow2: marshmallow>=2.2.0,<3.0.0
+ marshmallow3: marshmallow>=3.0.0rc5,<4.0.0
extras =
tests
full: apispec,jwt
|
4degrees__clique-26
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"source/clique/collection.py:Collection.format"
],
"edited_modules": [
"source/clique/collection.py:Collection"
]
},
"file": "source/clique/collection.py"
}
] |
4degrees/clique
|
a89507304acce5931f940c34025a6547fa8227b5
|
collection.format hits maximum recursion depth for collections with lots of holes.
The following code gives an example.
```python
paths = ["name.{0:04d}.jpg".format(x) for x in range(2000)[::2]]
collection = clique.assemble(paths)[0][0]
collection.format("{head}####{tail}")
```
|
diff --git a/source/clique/collection.py b/source/clique/collection.py
index 0c3b296..db9276c 100644
--- a/source/clique/collection.py
+++ b/source/clique/collection.py
@@ -251,15 +251,25 @@ class Collection(object):
else:
data['padding'] = '%d'
- if self.indexes:
+ if '{holes}' in pattern:
data['holes'] = self.holes().format('{ranges}')
+ if '{range}' in pattern or '{ranges}' in pattern:
indexes = list(self.indexes)
- if len(indexes) == 1:
+ indexes_count = len(indexes)
+
+ if indexes_count == 0:
+ data['range'] = ''
+
+ elif indexes_count == 1:
data['range'] = '{0}'.format(indexes[0])
+
else:
- data['range'] = '{0}-{1}'.format(indexes[0], indexes[-1])
+ data['range'] = '{0}-{1}'.format(
+ indexes[0], indexes[-1]
+ )
+ if '{ranges}' in pattern:
separated = self.separate()
if len(separated) > 1:
ranges = [collection.format('{range}')
@@ -270,11 +280,6 @@ class Collection(object):
data['ranges'] = ', '.join(ranges)
- else:
- data['holes'] = ''
- data['range'] = ''
- data['ranges'] = ''
-
return pattern.format(**data)
def is_contiguous(self):
|
6si__shipwright-79
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"shipwright/base.py:Shipwright.__init__",
"shipwright/base.py:Shipwright._build"
],
"edited_modules": [
"shipwright/base.py:Shipwright"
]
},
"file": "shipwright/base.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"shipwright/build.py:do_build",
"shipwright/build.py:build"
],
"edited_modules": [
"shipwright/build.py:do_build",
"shipwright/build.py:build"
]
},
"file": "shipwright/build.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"shipwright/cli.py:argparser",
"shipwright/cli.py:old_style_arg_dict",
"shipwright/cli.py:run"
],
"edited_modules": [
"shipwright/cli.py:argparser",
"shipwright/cli.py:old_style_arg_dict",
"shipwright/cli.py:run"
]
},
"file": "shipwright/cli.py"
}
] |
6si/shipwright
|
7d3ccf39acc79bb6d33a787e773227358764dd2c
|
docker pull all images for current branch and master before building
Because our buildserver forgets the docker cache between builds we pull the previous build for all the images.
it would be great if we could get shipwright to do it.
Otherwise a command like "shipright images" which lists all the images that shipwright *would* build would let us write our own command to do this.
|
diff --git a/CHANGES.rst b/CHANGES.rst
index f034d37..89cf5f1 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,7 +1,8 @@
0.5.1 (unreleased)
------------------
-- Nothing changed yet.
+- Add --pull-cache to pull images from repository before building.
+ (`Issue #49 <https://github.com/6si/shipwright/issues/49>`_).
0.5.0 (2016-08-19)
diff --git a/shipwright/base.py b/shipwright/base.py
index 213d597..421f1af 100644
--- a/shipwright/base.py
+++ b/shipwright/base.py
@@ -4,10 +4,11 @@ from . import build, dependencies, docker, push
class Shipwright(object):
- def __init__(self, source_control, docker_client, tags):
+ def __init__(self, source_control, docker_client, tags, pull_cache=False):
self.source_control = source_control
self.docker_client = docker_client
self.tags = tags
+ self._pull_cache = pull_cache
def targets(self):
return self.source_control.targets()
@@ -18,7 +19,10 @@ class Shipwright(object):
return self._build(this_ref_str, targets)
def _build(self, this_ref_str, targets):
- for evt in build.do_build(self.docker_client, this_ref_str, targets):
+ client = self.docker_client
+ pull_cache = self._pull_cache
+ ref = this_ref_str
+ for evt in build.do_build(client, ref, targets, pull_cache):
yield evt
# now that we're built and tagged all the images.
diff --git a/shipwright/build.py b/shipwright/build.py
index 707d4f9..4ee1558 100644
--- a/shipwright/build.py
+++ b/shipwright/build.py
@@ -13,7 +13,7 @@ def _merge(d1, d2):
return d
-def do_build(client, build_ref, targets):
+def do_build(client, build_ref, targets, pull_cache):
"""
Generic function for building multiple images while
notifying a callback function with output produced.
@@ -39,11 +39,11 @@ def do_build(client, build_ref, targets):
parent_ref = None
if target.parent:
parent_ref = build_index.get(target.parent)
- for evt in build(client, parent_ref, target):
+ for evt in build(client, parent_ref, target, pull_cache):
yield evt
-def build(client, parent_ref, image):
+def build(client, parent_ref, image, pull_cache):
"""
builds the given image tagged with <build_ref> and ensures that
it depends on it's parent if it's part of this build group (shares
@@ -62,7 +62,25 @@ def build(client, parent_ref, image):
built_tags = docker.last_built_from_docker(client, image.name)
if image.ref in built_tags:
- return []
+ return
+
+ if pull_cache:
+ pull_evts = client.pull(
+ repository=image.name,
+ tag=image.ref,
+ stream=True,
+ )
+
+ failed = False
+ for evt in pull_evts:
+ event = process_event_(evt)
+ if 'error' in event:
+ failed = True
+ else:
+ yield event
+
+ if not failed:
+ return
build_evts = client.build(
fileobj=mkcontext(parent_ref, image.path),
@@ -73,4 +91,5 @@ def build(client, parent_ref, image):
dockerfile=os.path.basename(image.path),
)
- return (process_event_(evt) for evt in build_evts)
+ for evt in build_evts:
+ yield process_event_(evt)
diff --git a/shipwright/cli.py b/shipwright/cli.py
index 24f6f78..82eaf50 100644
--- a/shipwright/cli.py
+++ b/shipwright/cli.py
@@ -109,6 +109,11 @@ def argparser():
help='Build working tree, including uncommited and untracked changes',
action='store_true',
)
+ common.add_argument(
+ '--pull-cache',
+ help='When building try to pull previously built images',
+ action='store_true',
+ )
a_arg(
common, '-d', '--dependants',
help='Build DEPENDANTS and all its dependants',
@@ -157,7 +162,6 @@ def old_style_arg_dict(namespace):
'--exclude': _flatten(ns.exclude),
'--help': False,
'--no-build': getattr(ns, 'no_build', False),
- '--dirty': getattr(ns, 'dirty', False),
'--upto': _flatten(ns.upto),
'--x-assert-hostname': ns.x_assert_hostname,
'-H': ns.docker_host,
@@ -237,8 +241,10 @@ def run(path, arguments, client_cfg, environ, new_style_args=None):
if new_style_args is None:
dirty = False
+ pull_cache = False
else:
dirty = new_style_args.dirty
+ pull_cache = new_style_args.pull_cache
namespace = config['namespace']
name_map = config.get('names', {})
@@ -249,7 +255,7 @@ def run(path, arguments, client_cfg, environ, new_style_args=None):
'to commit these changes, re-run with the --dirty flag.'
)
- sw = Shipwright(scm, client, arguments['tags'])
+ sw = Shipwright(scm, client, arguments['tags'], pull_cache)
command = getattr(sw, command_name)
show_progress = sys.stdout.isatty()
|
AI-SDC__AI-SDC-94
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"aisdc/attacks/report.py:NumpyArrayEncoder.default"
],
"edited_modules": [
"aisdc/attacks/report.py:NumpyArrayEncoder"
]
},
"file": "aisdc/attacks/report.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"aisdc/attacks/worst_case_attack.py:WorstCaseAttackArgs.__init__",
"aisdc/attacks/worst_case_attack.py:WorstCaseAttack.attack",
"aisdc/attacks/worst_case_attack.py:WorstCaseAttack.attack_from_preds",
"aisdc/attacks/worst_case_attack.py:WorstCaseAttack._prepare_attack_data",
"aisdc/attacks/worst_case_attack.py:WorstCaseAttack.run_attack_reps"
],
"edited_modules": [
"aisdc/attacks/worst_case_attack.py:WorstCaseAttackArgs",
"aisdc/attacks/worst_case_attack.py:WorstCaseAttack"
]
},
"file": "aisdc/attacks/worst_case_attack.py"
}
] |
AI-SDC/AI-SDC
|
a42a2110ade262a7d699d5b71cfccbc787290d5d
|
Add option to include target model error into attacks as a feature
Whether or not the target model classifies an example correctly provides some signal that could be of use to an attacker. We currently do not use this in the attacks, but should include an option to allow it.
The 0/1 loss between the predicted class and the actual class (binary feature) should be added for the worst case attack.
|
diff --git a/aisdc/attacks/report.py b/aisdc/attacks/report.py
index 12b3887..515c709 100644
--- a/aisdc/attacks/report.py
+++ b/aisdc/attacks/report.py
@@ -1,4 +1,5 @@
"""Code for automatic report generation"""
+import abc
import json
import numpy as np
@@ -83,6 +84,8 @@ class NumpyArrayEncoder(json.JSONEncoder):
return int(o)
if isinstance(o, np.int32):
return int(o)
+ if isinstance(o, abc.ABCMeta):
+ return str(o)
return json.JSONEncoder.default(self, o)
diff --git a/aisdc/attacks/worst_case_attack.py b/aisdc/attacks/worst_case_attack.py
index 28e6512..361822c 100644
--- a/aisdc/attacks/worst_case_attack.py
+++ b/aisdc/attacks/worst_case_attack.py
@@ -14,6 +14,7 @@ from typing import Any
import numpy as np
import sklearn
from sklearn.ensemble import RandomForestClassifier
+from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from aisdc.attacks import metrics, report
@@ -40,7 +41,14 @@ class WorstCaseAttackArgs:
self.__dict__["in_sample_filename"] = None
self.__dict__["out_sample_filename"] = None
self.__dict__["report_name"] = None
+ self.__dict__["include_model_correct_feature"] = False
self.__dict__["sort_probs"] = True
+ self.__dict__["mia_attack_model"] = RandomForestClassifier
+ self.__dict__["mia_attack_model_hyp"] = {
+ "min_samples_split": 20,
+ "min_samples_leaf": 10,
+ "max_depth": 5,
+ }
self.__dict__.update(kwargs)
def __str__(self):
@@ -83,7 +91,20 @@ class WorstCaseAttack(Attack):
"""
train_preds = target_model.predict_proba(dataset.x_train)
test_preds = target_model.predict_proba(dataset.x_test)
- self.attack_from_preds(train_preds, test_preds)
+ train_correct = None
+ test_correct = None
+ if self.args.include_model_correct_feature:
+ train_correct = 1 * (
+ dataset.y_train == target_model.predict(dataset.x_train)
+ )
+ test_correct = 1 * (dataset.y_test == target_model.predict(dataset.x_test))
+
+ self.attack_from_preds(
+ train_preds,
+ test_preds,
+ train_correct=train_correct,
+ test_correct=test_correct,
+ )
def attack_from_prediction_files(self):
"""Start an attack from saved prediction files
@@ -98,7 +119,11 @@ class WorstCaseAttack(Attack):
self.attack_from_preds(train_preds, test_preds)
def attack_from_preds( # pylint: disable=too-many-locals
- self, train_preds: np.ndarray, test_preds: np.ndarray
+ self,
+ train_preds: np.ndarray,
+ test_preds: np.ndarray,
+ train_correct: np.ndarray = None,
+ test_correct: np.ndarray = None,
) -> None:
"""
Runs the attack based upon the predictions in train_preds and test_preds, and the params
@@ -115,7 +140,13 @@ class WorstCaseAttack(Attack):
"""
logger = logging.getLogger("attack-from-preds")
logger.info("Running main attack repetitions")
- self.attack_metrics = self.run_attack_reps(train_preds, test_preds)
+ self.attack_metrics = self.run_attack_reps(
+ train_preds,
+ test_preds,
+ train_correct=train_correct,
+ test_correct=test_correct,
+ )
+
if self.args.n_dummy_reps > 0:
logger.info("Running dummy attack reps")
self.dummy_attack_metrics = []
@@ -130,7 +161,11 @@ class WorstCaseAttack(Attack):
logger.info("Finished running attacks")
def _prepare_attack_data(
- self, train_preds: np.ndarray, test_preds: np.ndarray
+ self,
+ train_preds: np.ndarray,
+ test_preds: np.ndarray,
+ train_correct: np.ndarray = None,
+ test_correct: np.ndarray = None,
) -> tuple[np.ndarray, np.ndarray]:
"""Prepare training data and labels for attack model
Combines the train and test preds into a single numpy array (optionally) sorting each
@@ -143,12 +178,23 @@ class WorstCaseAttack(Attack):
test_preds = -np.sort(-test_preds, axis=1)
logger.info("Creating MIA data")
+
+ if self.args.include_model_correct_feature and train_correct is not None:
+ train_preds = np.hstack((train_preds, train_correct[:, None]))
+ test_preds = np.hstack((test_preds, test_correct[:, None]))
+
mi_x = np.vstack((train_preds, test_preds))
mi_y = np.hstack((np.ones(len(train_preds)), np.zeros(len(test_preds))))
return (mi_x, mi_y)
- def run_attack_reps(self, train_preds: np.ndarray, test_preds: np.ndarray) -> list:
+ def run_attack_reps( # pylint: disable = too-many-locals
+ self,
+ train_preds: np.ndarray,
+ test_preds: np.ndarray,
+ train_correct: np.ndarray = None,
+ test_correct: np.ndarray = None,
+ ) -> list:
"""
Run actual attack reps from train and test predictions
@@ -167,8 +213,9 @@ class WorstCaseAttack(Attack):
self.args.set_param("n_rows_in", len(train_preds))
self.args.set_param("n_rows_out", len(test_preds))
logger = logging.getLogger("attack-reps")
-
- mi_x, mi_y = self._prepare_attack_data(train_preds, test_preds)
+ mi_x, mi_y = self._prepare_attack_data(
+ train_preds, test_preds, train_correct, test_correct
+ )
mia_metrics = []
for rep in range(self.args.n_reps):
@@ -176,13 +223,25 @@ class WorstCaseAttack(Attack):
mi_train_x, mi_test_x, mi_train_y, mi_test_y = train_test_split(
mi_x, mi_y, test_size=self.args.test_prop, stratify=mi_y
)
- attack_classifier = RandomForestClassifier()
+ attack_classifier = self.args.mia_attack_model(
+ **self.args.mia_attack_model_hyp
+ )
attack_classifier.fit(mi_train_x, mi_train_y)
mia_metrics.append(
metrics.get_metrics(attack_classifier, mi_test_x, mi_test_y)
)
+ if self.args.include_model_correct_feature and train_correct is not None:
+ # Compute the Yeom TPR and FPR
+ yeom_preds = mi_test_x[:, -1]
+ tn, fp, fn, tp = confusion_matrix(mi_test_y, yeom_preds).ravel()
+ mia_metrics[-1]["yeom_tpr"] = tp / (tp + fn)
+ mia_metrics[-1]["yeom_fpr"] = fp / (fp + tn)
+ mia_metrics[-1]["yeom_advantage"] = (
+ mia_metrics[-1]["yeom_tpr"] - mia_metrics[-1]["yeom_fpr"]
+ )
+
logger.info("Finished simulating attacks")
return mia_metrics
@@ -554,6 +613,21 @@ def main():
help=("P-value threshold for significance testing. Default = %(default)f"),
)
+ # Not currently possible from the command line as we cannot compute the correctness
+ # of predictions. Possibly to be added in the future
+ # attack_parser.add_argument(
+ # "--include-correct",
+ # action="store",
+ # type=bool,
+ # required=False,
+ # default=False,
+ # dest='include_model_correct_feature',
+ # help=(
+ # "Whether or not to include an additional feature into the MIA attack model that "
+ # "holds whether or not the target model made a correct predicion for each example."
+ # ),
+ # )
+
attack_parser.add_argument(
"--sort-probs",
action="store",
|
AI4S2S__lilio-58
|
[
{
"changes": {
"added_entities": [
"lilio/calendar.py:Calendar.n_precursors"
],
"added_modules": null,
"edited_entities": [
"lilio/calendar.py:Calendar.n_targets"
],
"edited_modules": [
"lilio/calendar.py:Calendar"
]
},
"file": "lilio/calendar.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"lilio/resampling.py:resample"
],
"edited_modules": [
"lilio/resampling.py:resample"
]
},
"file": "lilio/resampling.py"
}
] |
AI4S2S/lilio
|
416ea560d41b57502cf204fbf4e65e79c21373bf
|
Unclear error message when an empty calendar is passed to `resample` function.
When executing the following code:
```py
import lilio
from lilio import Calendar
import xarray as xr
ds = xr.load_dataset(path_to_data) # just some sample data
cal = Calendar("12-25")
# note that no intervals are added to the calendar
# cal.add_intervals("target", length="7d")
# cal.add_intervals("precursor", length="7d")
cal.map_to_data(ds)
data_resampled = lilio.resample(cal, ds)
```
This will trigger the following `ValueError`
```py
File [~/AI4S2S/lilio/lilio/resampling.py:342](https://vscode-remote+wsl-002bubuntu-002d20-002e04.vscode-resource.vscode-cdn.net/home/yangliu/AI4S2S/lilio/docs/notebooks/~/AI4S2S/lilio/lilio/resampling.py:342), in resample(calendar, input_data, how)
340 _check_valid_resampling_methods(how)
341 utils.check_timeseries(input_data)
--> 342 utils.check_input_frequency(calendar, input_data)
343 utils.check_reserved_names(input_data)
345 if isinstance(input_data, (pd.Series, pd.DataFrame)):
File [~/AI4S2S/lilio/lilio/utils.py:158](https://vscode-remote+wsl-002bubuntu-002d20-002e04.vscode-resource.vscode-cdn.net/home/yangliu/AI4S2S/lilio/docs/notebooks/~/AI4S2S/lilio/lilio/utils.py:158), in check_input_frequency(calendar, data)
151 """Compare the frequency of (input) data to the frequency of the calendar.
152
153 Note: Pandas and xarray have the builtin function `infer_freq`, but this function is
154 not robust enough for our purpose, so we have to manually infer the frequency if the
155 builtin one fails.
156 """
157 data_freq = infer_input_data_freq(data)
--> 158 calendar_freq = get_smallest_calendar_freq(calendar)
160 if calendar_freq < data_freq:
161 raise ValueError(
162 "The data is of a lower time resolution than the calendar. "
163 "This would lead to incorrect data and/or NaN values in the resampled data."
(...)
167 f"{str(calendar_freq)}"
168 )
File [~/AI4S2S/lilio/lilio/utils.py:145](https://vscode-remote+wsl-002bubuntu-002d20-002e04.vscode-resource.vscode-cdn.net/home/yangliu/AI4S2S/lilio/docs/notebooks/~/AI4S2S/lilio/lilio/utils.py:145), in get_smallest_calendar_freq(calendar)
143 lengthstr = [replace_month_length(ln) if ln[-1] == "M" else ln for ln in lengthstr]
144 lengths = [pd.Timedelta(ln) for ln in lengthstr]
--> 145 return min(lengths)
ValueError: min() arg is an empty sequence
```
The error message is not informative. It should remind the user to add intervals to the calendar. This needs to be fixed in the check for `resample` function, in `utils` module.
|
diff --git a/lilio/calendar.py b/lilio/calendar.py
index c288ebb..93ee1db 100644
--- a/lilio/calendar.py
+++ b/lilio/calendar.py
@@ -206,10 +206,15 @@ class Calendar:
self._set_mapping(mapping)
@property
- def n_targets(self):
+ def n_targets(self) -> int:
"""Return the number of targets."""
return len(self.targets)
+ @property
+ def n_precursors(self) -> int:
+ """Return the number of precursors."""
+ return len(self.precursors)
+
@property
def anchor(self):
"""Return the anchor."""
diff --git a/lilio/resampling.py b/lilio/resampling.py
index b426dbd..aa729d5 100644
--- a/lilio/resampling.py
+++ b/lilio/resampling.py
@@ -335,6 +335,8 @@ def resample(
"""
if calendar.mapping is None:
raise ValueError("Generate a calendar map before calling resample")
+ if calendar.n_targets + calendar.n_precursors == 0:
+ raise ValueError("The calendar has no intervals: resampling is not possible.")
if isinstance(how, str):
_check_valid_resampling_methods(how)
|
AI4S2S__s2spy-106
|
[
{
"changes": {
"added_entities": [
"s2spy/rgdr/rgdr.py:RGDR.preview_correlation",
"s2spy/rgdr/rgdr.py:RGDR.preview_clusters"
],
"added_modules": null,
"edited_entities": [
"s2spy/rgdr/rgdr.py:RGDR.plot_correlation",
"s2spy/rgdr/rgdr.py:RGDR.plot_clusters"
],
"edited_modules": [
"s2spy/rgdr/rgdr.py:RGDR"
]
},
"file": "s2spy/rgdr/rgdr.py"
}
] |
AI4S2S/s2spy
|
81682c3a15708eb9fccb705796b134933001afb4
|
Merge the plotting functionalities in RGDR module
Currently in RGDR module, there are two ways to plot the clusters:
- Preview the clusters by `RGDR(...).plot_clusters(precursor_field, target_timeseries)`
- Plotting clusters after fitting and transforming `cluster_map.cluster_labels[0].plot()`
The first option was designed to let the user have a quick check and preview the clusters. But it can cause confusion. We can merge these two functionalities and ask the user to `fit/transform` first and then `plot` the clusters.
|
diff --git a/notebooks/tutorial_RGDR.ipynb b/notebooks/tutorial_RGDR.ipynb
index 84f5228..0f8213a 100644
--- a/notebooks/tutorial_RGDR.ipynb
+++ b/notebooks/tutorial_RGDR.ipynb
@@ -76,14 +76,27 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Using `.plot_correlation` we can see the correlation and p-value map of the target timeseries and precursor field:"
+ "Using `.preview_correlation` we can visualize the correlation and p-value map of the target timeseries and precursor field, for a single lag.\n",
+ "\n",
+ "In this case we use lag `1`."
]
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": 7,
"metadata": {},
"outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[<matplotlib.collections.QuadMesh at 0x1a0501cb6d0>,\n",
+ " <matplotlib.collections.QuadMesh at 0x1a063a29270>]"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ },
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAArwAAACqCAYAAABPqpzsAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAA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cOaG7zWqHcCl0REN7BK0u+BtwJ/Au6KiBUAkhYB04D1wGMR8Xj6+kuAuYO4/ruB7wNExP2S7k/Pv53k9tptaeIdBdw+iOuYmbUD52wb1tzgtTxsKNnvZnB/Z128NvRmdB3lBdwQEccM4ppmZsOJc7a1PY/htUb9P+BjkjolbUfy7f2uKuUfAt4oaVp6/LEK5dYB40qOlwMHpPsfLjl/K/BxAEl7AXun5+8guR23a/qzsZJ2q+cXMjNrY87ZNqy5wWuNugq4H7gP+B3w5Yh4tlLhiHgZ+DzwW0kLSZLkS2WKXgqcLOleSbsA3waOl3QvybizXv8BbCVpKclYr4XpdZ4D5gCXpLfMbgfeNJhf1MysDThn27CmiGh2DDZMSNoqItanTwCfBzwSEec2Oy4zM9ucc7a1E/fw2lD6bPpAxAPA1iRPAJuZWTE5Z1vbcA+vmZmZmbU19/CamZmZWVtzg9fMzMzM2pobvGZmZmbW1tzgNTMzM7O25gavmZmZmbU1N3jNzMzMrK39f+qLTKkPu+CbAAAAAElFTkSuQmCC",
@@ -99,23 +112,33 @@
],
"source": [
"fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 2))\n",
- "_ = rgdr.plot_correlation(precursor_field, target_timeseries, lag=1, ax1=ax1, ax2=ax2)"
+ "rgdr.preview_correlation(precursor_field, target_timeseries, lag=1, ax1=ax1, ax2=ax2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "We can compare two RGDR initializations to preview what the effect on the generated clusters will be.\n",
+ "Using the preview utilities we can compare two RGDR setups, and see what the effect on the generated clusters will be.\n",
"\n",
"Note that the second figure has an extra cluster, due to the minimum area argument having a smaller value."
]
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": 6,
"metadata": {},
"outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "<matplotlib.collections.QuadMesh at 0x1a063c76b60>"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ },
{
"data": {
"image/png": "iVBORw0KGgo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tClFb8FFEyz/a+BpkrYtn79pnOXuBzbseL4ceF75+A0d888H3gogaWdgl3L+YorDhjuUr60v6Rm9fKCIiBZLZkdMQxrKMV2nAkuBK4CfAx+xfdt4C9t+CHgfcKakSynC9Y9dFj0B+LCkyyVtD3wJeK+kyynG1Y34V2ADSddSjGW7tNzOH4B3AMeXh/YuAJ41kw8aEdECyeyIaZDtqmuIWULSBrYfKM+o/jrwG9tHVl1XREQ8XjI7Ij3KMVzvLk8UuRp4IsUZ1RERUU/J7Jj10qMcEREREdFFepQjIiIiIrpIQzkiIiIioos0lCMiIiIiukhDOSIiIiKiizSUIyIiIiK6SEM5IiIiIqKL/w8vMXfrLf0D1gAAAABJRU5ErkJggg==",
@@ -132,17 +155,21 @@
"source": [
"fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 2))\n",
"\n",
- "_ = rgdr.plot_clusters(precursor_field, target_timeseries, lag=1, ax=ax1)\n",
+ "RGDR(eps_km=600, min_area_km2=3000**2).preview_clusters(precursor_field,\n",
+ " target_timeseries,\n",
+ " lag=1, ax=ax1)\n",
"\n",
- "_ = RGDR(eps_km=600, min_area_km2=None).plot_clusters(precursor_field, target_timeseries,\n",
- " lag=1, ax=ax2)"
+ "RGDR(eps_km=600, min_area_km2=None).preview_clusters(precursor_field,\n",
+ " target_timeseries,\n",
+ " lag=1, ax=ax2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "With `.fit` the RGDR clustering can be fit to a precursor field.\n",
+ "Once you are satisfied with the selected paramters, the `.fit` method can be used to fit the RGDR clustering to a precursor field.\n",
+ "\n",
"`.transform` can then be used to return the data reduced to clusters:"
]
},
@@ -515,7 +542,7 @@
" longitude (cluster_labels) float64 223.9 185.4 221.8 190.2 217.8 219.3\n",
"Attributes:\n",
" data: Clustered data with Response Guided Dimensionality Reduction.\n",
- " coordinates: Latitudes and longitudes are geographical centers associate...</pre><div class='xr-wrap' style='display:none'><div class='xr-header'><div class='xr-obj-type'>xarray.DataArray</div><div class='xr-array-name'>'sst'</div><ul class='xr-dim-list'><li><span class='xr-has-index'>anchor_year</span>: 39</li><li><span class='xr-has-index'>cluster_labels</span>: 6</li></ul></div><ul class='xr-sections'><li class='xr-section-item'><div class='xr-array-wrap'><input id='section-ebb62979-6703-4d4f-9e66-216747b50a2f' class='xr-array-in' type='checkbox' ><label for='section-ebb62979-6703-4d4f-9e66-216747b50a2f' title='Show/hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-array-preview xr-preview'><span>290.8 298.9 287.8 296.6 286.0 284.9 ... 298.2 288.4 296.6 286.9 285.1</span></div><div class='xr-array-data'><pre>array([[290.79588914, 298.94548042, 287.83356654, 296.5913755 ,\n",
+ " coordinates: Latitudes and longitudes are geographical centers associate...</pre><div class='xr-wrap' style='display:none'><div class='xr-header'><div class='xr-obj-type'>xarray.DataArray</div><div class='xr-array-name'>'sst'</div><ul class='xr-dim-list'><li><span class='xr-has-index'>anchor_year</span>: 39</li><li><span class='xr-has-index'>cluster_labels</span>: 6</li></ul></div><ul class='xr-sections'><li class='xr-section-item'><div class='xr-array-wrap'><input id='section-b9814065-77d7-499d-bf20-524974fa3294' class='xr-array-in' type='checkbox' ><label for='section-b9814065-77d7-499d-bf20-524974fa3294' title='Show/hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-array-preview xr-preview'><span>290.8 298.9 287.8 296.6 286.0 284.9 ... 298.2 288.4 296.6 286.9 285.1</span></div><div class='xr-array-data'><pre>array([[290.79588914, 298.94548042, 287.83356654, 296.5913755 ,\n",
" 286.03044129, 284.87776786],\n",
" [290.970545 , 298.92119198, 288.55306112, 296.90258837,\n",
" 286.41065088, 285.21587978],\n",
@@ -555,13 +582,13 @@
" [291.45966391, 299.19568083, 288.59732323, 296.99780806,\n",
" 286.61949986, 284.98540926],\n",
" [291.37066195, 298.21053747, 288.43352188, 296.60848274,\n",
- " 286.90046576, 285.06801918]])</pre></div></div></li><li class='xr-section-item'><input id='section-3a5d483f-c7dd-4c8e-89c9-63da712b7ba6' class='xr-section-summary-in' type='checkbox' checked><label for='section-3a5d483f-c7dd-4c8e-89c9-63da712b7ba6' class='xr-section-summary' >Coordinates: <span>(4)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>anchor_year</span></div><div class='xr-var-dims'>(anchor_year)</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>1980 1981 1982 ... 2016 2017 2018</div><input id='attrs-8e70b916-84d8-40d9-918a-209ea4c71272' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-8e70b916-84d8-40d9-918a-209ea4c71272' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-a088dd2e-4ea3-49c5-b26a-bec2841de5d3' class='xr-var-data-in' type='checkbox'><label for='data-a088dd2e-4ea3-49c5-b26a-bec2841de5d3' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991,\n",
+ " 286.90046576, 285.06801918]])</pre></div></div></li><li class='xr-section-item'><input id='section-8ab02218-59be-4b93-a221-54e4749a4c78' class='xr-section-summary-in' type='checkbox' checked><label for='section-8ab02218-59be-4b93-a221-54e4749a4c78' class='xr-section-summary' >Coordinates: <span>(4)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>anchor_year</span></div><div class='xr-var-dims'>(anchor_year)</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>1980 1981 1982 ... 2016 2017 2018</div><input id='attrs-e7d9a151-f6d5-4bdc-8098-860833f05ce3' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-e7d9a151-f6d5-4bdc-8098-860833f05ce3' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-4933660f-689b-4cff-bf5a-9f595f3ddc32' class='xr-var-data-in' type='checkbox'><label for='data-4933660f-689b-4cff-bf5a-9f595f3ddc32' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991,\n",
" 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,\n",
" 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,\n",
- " 2016, 2017, 2018])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>cluster_labels</span></div><div class='xr-var-dims'>(cluster_labels)</div><div class='xr-var-dtype'><U20</div><div class='xr-var-preview xr-preview'>'lag:1_cluster:-2' ... 'lag:4_cl...</div><input id='attrs-3951033c-4bfd-451e-9fb2-0927e2b3c321' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-3951033c-4bfd-451e-9fb2-0927e2b3c321' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-d6752cfe-c010-420c-855e-8b2ebd984b5f' class='xr-var-data-in' type='checkbox'><label for='data-d6752cfe-c010-420c-855e-8b2ebd984b5f' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array(['lag:1_cluster:-2', 'lag:1_cluster:1', 'lag:2_cluster:-1',\n",
- " 'lag:2_cluster:1', 'lag:3_cluster:-1', 'lag:4_cluster:-2'], dtype='<U20')</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>latitude</span></div><div class='xr-var-dims'>(cluster_labels)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>36.05 29.44 37.33 29.58 38.14 39.78</div><input id='attrs-1e9d0a47-a70a-4a4a-a32d-6fdabbe7af38' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-1e9d0a47-a70a-4a4a-a32d-6fdabbe7af38' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-d7b33e7f-ab59-4715-8dac-97820938005b' class='xr-var-data-in' type='checkbox'><label for='data-d7b33e7f-ab59-4715-8dac-97820938005b' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([36.0508552 , 29.4398051 , 37.33257702, 29.58134561, 38.13773082,\n",
- " 39.78162825])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>longitude</span></div><div class='xr-var-dims'>(cluster_labels)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>223.9 185.4 221.8 190.2 217.8 219.3</div><input id='attrs-140e577b-192d-4ef3-aa46-3cacf76cf2b5' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-140e577b-192d-4ef3-aa46-3cacf76cf2b5' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-1a127e1f-5fae-4c9a-b627-bda596ae2de7' class='xr-var-data-in' type='checkbox'><label for='data-1a127e1f-5fae-4c9a-b627-bda596ae2de7' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([223.86658208, 185.40970765, 221.82516648, 190.20336403,\n",
- " 217.7810629 , 219.30300121])</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-52ed9bea-fa67-4733-a041-2bd5da86e1af' class='xr-section-summary-in' type='checkbox' checked><label for='section-52ed9bea-fa67-4733-a041-2bd5da86e1af' class='xr-section-summary' >Attributes: <span>(2)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><dl class='xr-attrs'><dt><span>data :</span></dt><dd>Clustered data with Response Guided Dimensionality Reduction.</dd><dt><span>coordinates :</span></dt><dd>Latitudes and longitudes are geographical centers associated with clusters.</dd></dl></div></li></ul></div></div>"
+ " 2016, 2017, 2018])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>cluster_labels</span></div><div class='xr-var-dims'>(cluster_labels)</div><div class='xr-var-dtype'><U20</div><div class='xr-var-preview xr-preview'>'lag:1_cluster:-2' ... 'lag:4_cl...</div><input id='attrs-a3775c40-6ebc-4a42-bf0e-e3037a18ad11' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-a3775c40-6ebc-4a42-bf0e-e3037a18ad11' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-2c65aa63-0d9f-479a-9a52-6235fdbe351c' class='xr-var-data-in' type='checkbox'><label for='data-2c65aa63-0d9f-479a-9a52-6235fdbe351c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array(['lag:1_cluster:-2', 'lag:1_cluster:1', 'lag:2_cluster:-1',\n",
+ " 'lag:2_cluster:1', 'lag:3_cluster:-1', 'lag:4_cluster:-2'], dtype='<U20')</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>latitude</span></div><div class='xr-var-dims'>(cluster_labels)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>36.05 29.44 37.33 29.58 38.14 39.78</div><input id='attrs-5ec3591f-c5c0-42d9-a37e-83f52120d27f' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-5ec3591f-c5c0-42d9-a37e-83f52120d27f' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-b117a3f9-382c-430a-a83c-273c78962a08' class='xr-var-data-in' type='checkbox'><label for='data-b117a3f9-382c-430a-a83c-273c78962a08' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([36.0508552 , 29.4398051 , 37.33257702, 29.58134561, 38.13773082,\n",
+ " 39.78162825])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>longitude</span></div><div class='xr-var-dims'>(cluster_labels)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>223.9 185.4 221.8 190.2 217.8 219.3</div><input id='attrs-b30326c1-962c-4973-abcb-0fffdd76751c' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-b30326c1-962c-4973-abcb-0fffdd76751c' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-ca106886-bf06-4ac2-a980-c3df7cff353c' class='xr-var-data-in' type='checkbox'><label for='data-ca106886-bf06-4ac2-a980-c3df7cff353c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([223.86658208, 185.40970765, 221.82516648, 190.20336403,\n",
+ " 217.7810629 , 219.30300121])</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-df1be5c8-b32f-4819-812f-7c3936f2b85e' class='xr-section-summary-in' type='checkbox' checked><label for='section-df1be5c8-b32f-4819-812f-7c3936f2b85e' class='xr-section-summary' >Attributes: <span>(2)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><dl class='xr-attrs'><dt><span>data :</span></dt><dd>Clustered data with Response Guided Dimensionality Reduction.</dd><dt><span>coordinates :</span></dt><dd>Latitudes and longitudes are geographical centers associated with clusters.</dd></dl></div></li></ul></div></div>"
],
"text/plain": [
"<xarray.DataArray 'sst' (anchor_year: 39, cluster_labels: 6)>\n",
@@ -632,59 +659,471 @@
"plt.legend()"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The `RGDR` object will also contain the correlation maps, p-values, and cluster maps.\n",
+ "\n",
+ "These are all `xr.DataArray` objects, and can easily be plot using the builtin methods:"
+ ]
+ },
{
"cell_type": "code",
- "execution_count": 7,
+ "execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
+ "text/html": [
+ "<div><svg style=\"position: absolute; width: 0; height: 0; overflow: hidden\">\n",
+ "<defs>\n",
+ "<symbol id=\"icon-database\" viewBox=\"0 0 32 32\">\n",
+ "<path d=\"M16 0c-8.837 0-16 2.239-16 5v4c0 2.761 7.163 5 16 5s16-2.239 16-5v-4c0-2.761-7.163-5-16-5z\"></path>\n",
+ "<path d=\"M16 17c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n",
+ "<path d=\"M16 26c-8.837 0-16-2.239-16-5v6c0 2.761 7.163 5 16 5s16-2.239 16-5v-6c0 2.761-7.163 5-16 5z\"></path>\n",
+ "</symbol>\n",
+ "<symbol id=\"icon-file-text2\" viewBox=\"0 0 32 32\">\n",
+ "<path d=\"M28.681 7.159c-0.694-0.947-1.662-2.053-2.724-3.116s-2.169-2.030-3.116-2.724c-1.612-1.182-2.393-1.319-2.841-1.319h-15.5c-1.378 0-2.5 1.121-2.5 2.5v27c0 1.378 1.122 2.5 2.5 2.5h23c1.378 0 2.5-1.122 2.5-2.5v-19.5c0-0.448-0.137-1.23-1.319-2.841zM24.543 5.457c0.959 0.959 1.712 1.825 2.268 2.543h-4.811v-4.811c0.718 0.556 1.584 1.309 2.543 2.268zM28 29.5c0 0.271-0.229 0.5-0.5 0.5h-23c-0.271 0-0.5-0.229-0.5-0.5v-27c0-0.271 0.229-0.5 0.5-0.5 0 0 15.499-0 15.5 0v7c0 0.552 0.448 1 1 1h7v19.5z\"></path>\n",
+ "<path d=\"M23 26h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n",
+ "<path d=\"M23 22h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n",
+ "<path d=\"M23 18h-14c-0.552 0-1-0.448-1-1s0.448-1 1-1h14c0.552 0 1 0.448 1 1s-0.448 1-1 1z\"></path>\n",
+ "</symbol>\n",
+ "</defs>\n",
+ "</svg>\n",
+ "<style>/* CSS stylesheet for displaying xarray objects in jupyterlab.\n",
+ " *\n",
+ " */\n",
+ "\n",
+ ":root {\n",
+ " --xr-font-color0: var(--jp-content-font-color0, rgba(0, 0, 0, 1));\n",
+ " --xr-font-color2: var(--jp-content-font-color2, rgba(0, 0, 0, 0.54));\n",
+ " --xr-font-color3: var(--jp-content-font-color3, rgba(0, 0, 0, 0.38));\n",
+ " --xr-border-color: var(--jp-border-color2, #e0e0e0);\n",
+ " --xr-disabled-color: var(--jp-layout-color3, #bdbdbd);\n",
+ " --xr-background-color: var(--jp-layout-color0, white);\n",
+ " --xr-background-color-row-even: var(--jp-layout-color1, white);\n",
+ " --xr-background-color-row-odd: var(--jp-layout-color2, #eeeeee);\n",
+ "}\n",
+ "\n",
+ "html[theme=dark],\n",
+ "body[data-theme=dark],\n",
+ "body.vscode-dark {\n",
+ " --xr-font-color0: rgba(255, 255, 255, 1);\n",
+ " --xr-font-color2: rgba(255, 255, 255, 0.54);\n",
+ " --xr-font-color3: rgba(255, 255, 255, 0.38);\n",
+ " --xr-border-color: #1F1F1F;\n",
+ " --xr-disabled-color: #515151;\n",
+ " --xr-background-color: #111111;\n",
+ " --xr-background-color-row-even: #111111;\n",
+ " --xr-background-color-row-odd: #313131;\n",
+ "}\n",
+ "\n",
+ ".xr-wrap {\n",
+ " display: block !important;\n",
+ " min-width: 300px;\n",
+ " max-width: 700px;\n",
+ "}\n",
+ "\n",
+ ".xr-text-repr-fallback {\n",
+ " /* fallback to plain text repr when CSS is not injected (untrusted notebook) */\n",
+ " display: none;\n",
+ "}\n",
+ "\n",
+ ".xr-header {\n",
+ " padding-top: 6px;\n",
+ " padding-bottom: 6px;\n",
+ " margin-bottom: 4px;\n",
+ " border-bottom: solid 1px var(--xr-border-color);\n",
+ "}\n",
+ "\n",
+ ".xr-header > div,\n",
+ ".xr-header > ul {\n",
+ " display: inline;\n",
+ " margin-top: 0;\n",
+ " margin-bottom: 0;\n",
+ "}\n",
+ "\n",
+ ".xr-obj-type,\n",
+ ".xr-array-name {\n",
+ " margin-left: 2px;\n",
+ " margin-right: 10px;\n",
+ "}\n",
+ "\n",
+ ".xr-obj-type {\n",
+ " color: var(--xr-font-color2);\n",
+ "}\n",
+ "\n",
+ ".xr-sections {\n",
+ " padding-left: 0 !important;\n",
+ " display: grid;\n",
+ " grid-template-columns: 150px auto auto 1fr 20px 20px;\n",
+ "}\n",
+ "\n",
+ ".xr-section-item {\n",
+ " display: contents;\n",
+ "}\n",
+ "\n",
+ ".xr-section-item input {\n",
+ " display: none;\n",
+ "}\n",
+ "\n",
+ ".xr-section-item input + label {\n",
+ " color: var(--xr-disabled-color);\n",
+ "}\n",
+ "\n",
+ ".xr-section-item input:enabled + label {\n",
+ " cursor: pointer;\n",
+ " color: var(--xr-font-color2);\n",
+ "}\n",
+ "\n",
+ ".xr-section-item input:enabled + label:hover {\n",
+ " color: var(--xr-font-color0);\n",
+ "}\n",
+ "\n",
+ ".xr-section-summary {\n",
+ " grid-column: 1;\n",
+ " color: var(--xr-font-color2);\n",
+ " font-weight: 500;\n",
+ "}\n",
+ "\n",
+ ".xr-section-summary > span {\n",
+ " display: inline-block;\n",
+ " padding-left: 0.5em;\n",
+ "}\n",
+ "\n",
+ ".xr-section-summary-in:disabled + label {\n",
+ " color: var(--xr-font-color2);\n",
+ "}\n",
+ "\n",
+ ".xr-section-summary-in + label:before {\n",
+ " display: inline-block;\n",
+ " content: '►';\n",
+ " font-size: 11px;\n",
+ " width: 15px;\n",
+ " text-align: center;\n",
+ "}\n",
+ "\n",
+ ".xr-section-summary-in:disabled + label:before {\n",
+ " color: var(--xr-disabled-color);\n",
+ "}\n",
+ "\n",
+ ".xr-section-summary-in:checked + label:before {\n",
+ " content: '▼';\n",
+ "}\n",
+ "\n",
+ ".xr-section-summary-in:checked + label > span {\n",
+ " display: none;\n",
+ "}\n",
+ "\n",
+ ".xr-section-summary,\n",
+ ".xr-section-inline-details {\n",
+ " padding-top: 4px;\n",
+ " padding-bottom: 4px;\n",
+ "}\n",
+ "\n",
+ ".xr-section-inline-details {\n",
+ " grid-column: 2 / -1;\n",
+ "}\n",
+ "\n",
+ ".xr-section-details {\n",
+ " display: none;\n",
+ " grid-column: 1 / -1;\n",
+ " margin-bottom: 5px;\n",
+ "}\n",
+ "\n",
+ ".xr-section-summary-in:checked ~ .xr-section-details {\n",
+ " display: contents;\n",
+ "}\n",
+ "\n",
+ ".xr-array-wrap {\n",
+ " grid-column: 1 / -1;\n",
+ " display: grid;\n",
+ " grid-template-columns: 20px auto;\n",
+ "}\n",
+ "\n",
+ ".xr-array-wrap > label {\n",
+ " grid-column: 1;\n",
+ " vertical-align: top;\n",
+ "}\n",
+ "\n",
+ ".xr-preview {\n",
+ " color: var(--xr-font-color3);\n",
+ "}\n",
+ "\n",
+ ".xr-array-preview,\n",
+ ".xr-array-data {\n",
+ " padding: 0 5px !important;\n",
+ " grid-column: 2;\n",
+ "}\n",
+ "\n",
+ ".xr-array-data,\n",
+ ".xr-array-in:checked ~ .xr-array-preview {\n",
+ " display: none;\n",
+ "}\n",
+ "\n",
+ ".xr-array-in:checked ~ .xr-array-data,\n",
+ ".xr-array-preview {\n",
+ " display: inline-block;\n",
+ "}\n",
+ "\n",
+ ".xr-dim-list {\n",
+ " display: inline-block !important;\n",
+ " list-style: none;\n",
+ " padding: 0 !important;\n",
+ " margin: 0;\n",
+ "}\n",
+ "\n",
+ ".xr-dim-list li {\n",
+ " display: inline-block;\n",
+ " padding: 0;\n",
+ " margin: 0;\n",
+ "}\n",
+ "\n",
+ ".xr-dim-list:before {\n",
+ " content: '(';\n",
+ "}\n",
+ "\n",
+ ".xr-dim-list:after {\n",
+ " content: ')';\n",
+ "}\n",
+ "\n",
+ ".xr-dim-list li:not(:last-child):after {\n",
+ " content: ',';\n",
+ " padding-right: 5px;\n",
+ "}\n",
+ "\n",
+ ".xr-has-index {\n",
+ " font-weight: bold;\n",
+ "}\n",
+ "\n",
+ ".xr-var-list,\n",
+ ".xr-var-item {\n",
+ " display: contents;\n",
+ "}\n",
+ "\n",
+ ".xr-var-item > div,\n",
+ ".xr-var-item label,\n",
+ ".xr-var-item > .xr-var-name span {\n",
+ " background-color: var(--xr-background-color-row-even);\n",
+ " margin-bottom: 0;\n",
+ "}\n",
+ "\n",
+ ".xr-var-item > .xr-var-name:hover span {\n",
+ " padding-right: 5px;\n",
+ "}\n",
+ "\n",
+ ".xr-var-list > li:nth-child(odd) > div,\n",
+ ".xr-var-list > li:nth-child(odd) > label,\n",
+ ".xr-var-list > li:nth-child(odd) > .xr-var-name span {\n",
+ " background-color: var(--xr-background-color-row-odd);\n",
+ "}\n",
+ "\n",
+ ".xr-var-name {\n",
+ " grid-column: 1;\n",
+ "}\n",
+ "\n",
+ ".xr-var-dims {\n",
+ " grid-column: 2;\n",
+ "}\n",
+ "\n",
+ ".xr-var-dtype {\n",
+ " grid-column: 3;\n",
+ " text-align: right;\n",
+ " color: var(--xr-font-color2);\n",
+ "}\n",
+ "\n",
+ ".xr-var-preview {\n",
+ " grid-column: 4;\n",
+ "}\n",
+ "\n",
+ ".xr-var-name,\n",
+ ".xr-var-dims,\n",
+ ".xr-var-dtype,\n",
+ ".xr-preview,\n",
+ ".xr-attrs dt {\n",
+ " white-space: nowrap;\n",
+ " overflow: hidden;\n",
+ " text-overflow: ellipsis;\n",
+ " padding-right: 10px;\n",
+ "}\n",
+ "\n",
+ ".xr-var-name:hover,\n",
+ ".xr-var-dims:hover,\n",
+ ".xr-var-dtype:hover,\n",
+ ".xr-attrs dt:hover {\n",
+ " overflow: visible;\n",
+ " width: auto;\n",
+ " z-index: 1;\n",
+ "}\n",
+ "\n",
+ ".xr-var-attrs,\n",
+ ".xr-var-data {\n",
+ " display: none;\n",
+ " background-color: var(--xr-background-color) !important;\n",
+ " padding-bottom: 5px !important;\n",
+ "}\n",
+ "\n",
+ ".xr-var-attrs-in:checked ~ .xr-var-attrs,\n",
+ ".xr-var-data-in:checked ~ .xr-var-data {\n",
+ " display: block;\n",
+ "}\n",
+ "\n",
+ ".xr-var-data > table {\n",
+ " float: right;\n",
+ "}\n",
+ "\n",
+ ".xr-var-name span,\n",
+ ".xr-var-data,\n",
+ ".xr-attrs {\n",
+ " padding-left: 25px !important;\n",
+ "}\n",
+ "\n",
+ ".xr-attrs,\n",
+ ".xr-var-attrs,\n",
+ ".xr-var-data {\n",
+ " grid-column: 1 / -1;\n",
+ "}\n",
+ "\n",
+ "dl.xr-attrs {\n",
+ " padding: 0;\n",
+ " margin: 0;\n",
+ " display: grid;\n",
+ " grid-template-columns: 125px auto;\n",
+ "}\n",
+ "\n",
+ ".xr-attrs dt,\n",
+ ".xr-attrs dd {\n",
+ " padding: 0;\n",
+ " margin: 0;\n",
+ " float: left;\n",
+ " padding-right: 10px;\n",
+ " width: auto;\n",
+ "}\n",
+ "\n",
+ ".xr-attrs dt {\n",
+ " font-weight: normal;\n",
+ " grid-column: 1;\n",
+ "}\n",
+ "\n",
+ ".xr-attrs dt:hover span {\n",
+ " display: inline-block;\n",
+ " background: var(--xr-background-color);\n",
+ " padding-right: 10px;\n",
+ "}\n",
+ "\n",
+ ".xr-attrs dd {\n",
+ " grid-column: 2;\n",
+ " white-space: pre-wrap;\n",
+ " word-break: break-all;\n",
+ "}\n",
+ "\n",
+ ".xr-icon-database,\n",
+ ".xr-icon-file-text2 {\n",
+ " display: inline-block;\n",
+ " vertical-align: middle;\n",
+ " width: 1em;\n",
+ " height: 1.5em !important;\n",
+ " stroke-width: 0;\n",
+ " stroke: currentColor;\n",
+ " fill: currentColor;\n",
+ "}\n",
+ "</style><pre class='xr-text-repr-fallback'><xarray.DataArray (latitude: 5, longitude: 13, i_interval: 4)>\n",
+ "0.01618 -0.2187 -0.2194 -0.2663 0.02414 ... -0.3984 -0.38 -0.3063 -0.1126\n",
+ "Coordinates:\n",
+ " * i_interval (i_interval) int64 1 2 3 4\n",
+ " * latitude (latitude) float64 47.5 42.5 37.5 32.5 27.5\n",
+ " * longitude (longitude) float64 177.5 182.5 187.5 ... 227.5 232.5 237.5\n",
+ " area (latitude) float64 3.34e+06 3.645e+06 ... 4.169e+06 4.385e+06\n",
+ " tfreq int64 5\n",
+ " n_clusters int64 6\n",
+ " cluster int64 3</pre><div class='xr-wrap' style='display:none'><div class='xr-header'><div class='xr-obj-type'>xarray.DataArray</div><div class='xr-array-name'></div><ul class='xr-dim-list'><li><span class='xr-has-index'>latitude</span>: 5</li><li><span class='xr-has-index'>longitude</span>: 13</li><li><span class='xr-has-index'>i_interval</span>: 4</li></ul></div><ul class='xr-sections'><li class='xr-section-item'><div class='xr-array-wrap'><input id='section-420d8bed-40b7-4777-abcf-2c09c8b76ead' class='xr-array-in' type='checkbox' ><label for='section-420d8bed-40b7-4777-abcf-2c09c8b76ead' title='Show/hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-array-preview xr-preview'><span>0.01618 -0.2187 -0.2194 -0.2663 ... -0.3984 -0.38 -0.3063 -0.1126</span></div><div class='xr-array-data'><pre>array([[[ 0.01617516, -0.21868534, -0.21941745, -0.26630719],\n",
+ " [ 0.02414245, -0.12315571, -0.21464621, -0.18191947],\n",
+ " [-0.1105048 , -0.23253951, -0.4007449 , -0.25372747],\n",
+ " [-0.24520611, -0.35037825, -0.46371192, -0.35772739],\n",
+ " [-0.32824171, -0.4534247 , -0.46975605, -0.3473753 ],\n",
+ " [-0.323078 , -0.43326205, -0.41748415, -0.29461981],\n",
+ " [-0.30660624, -0.34313136, -0.34457092, -0.28702518],\n",
+ " [-0.38616188, -0.34666184, -0.37666874, -0.37721962],\n",
+ " [-0.3822271 , -0.33402403, -0.30240485, -0.32951966],\n",
+ " [-0.36827501, -0.41554246, -0.28493204, -0.33065629],\n",
+ " [-0.28047128, -0.27858467, -0.19205284, -0.27627975],\n",
+ " [-0.10757776, -0.2545805 , -0.15956299, -0.12823108],\n",
+ " [ nan, nan, nan, nan]],\n",
+ "\n",
+ " [[-0.02842247, -0.12801465, -0.1379688 , -0.19425886],\n",
+ " [ 0.00598683, -0.0124359 , -0.0967947 , -0.10557213],\n",
+ " [ 0.00479765, -0.09888618, -0.13544553, -0.1265711 ],\n",
+ " [ 0.01930277, -0.06881219, -0.16586661, -0.2325628 ],\n",
+ " [-0.01405595, -0.1865748 , -0.22187587, -0.25983436],\n",
+ " [ 0.01204043, -0.26110484, -0.28542316, -0.29141342],\n",
+ "...\n",
+ " [-0.18490648, -0.12178649, -0.12912278, -0.29769152],\n",
+ " [-0.24043321, -0.27218421, -0.25308925, -0.3604698 ],\n",
+ " [-0.29061517, -0.38322784, -0.34714351, -0.39152915],\n",
+ " [-0.35707131, -0.54341488, -0.46870146, -0.3338985 ],\n",
+ " [-0.26357851, -0.48241304, -0.36081808, -0.155657 ],\n",
+ " [-0.27768413, -0.32115578, -0.26949376, -0.10772449]],\n",
+ "\n",
+ " [[ 0.42487447, 0.50036829, 0.20242345, 0.01770287],\n",
+ " [ 0.34211447, 0.4839066 , 0.2784725 , 0.00806344],\n",
+ " [ 0.3433933 , 0.43694834, 0.3199787 , 0.14065339],\n",
+ " [ 0.18648733, 0.35050515, 0.33449607, 0.13369711],\n",
+ " [ 0.04340644, 0.25401412, 0.29487164, 0.1233588 ],\n",
+ " [-0.10334886, 0.09830805, 0.26352384, 0.0517264 ],\n",
+ " [-0.17111999, -0.08694884, 0.16013368, -0.01373979],\n",
+ " [-0.24750864, -0.25987983, -0.08067427, -0.06523411],\n",
+ " [-0.35825522, -0.39384288, -0.31606223, -0.1921587 ],\n",
+ " [-0.41354082, -0.4202639 , -0.34898835, -0.11634853],\n",
+ " [-0.37029449, -0.43487533, -0.35672934, -0.1791453 ],\n",
+ " [-0.40753351, -0.42768064, -0.34349675, -0.21013388],\n",
+ " [-0.39836497, -0.37996126, -0.3062787 , -0.11258559]]])</pre></div></div></li><li class='xr-section-item'><input id='section-fa2fda83-c99e-417a-8f36-df966d53fc7f' class='xr-section-summary-in' type='checkbox' checked><label for='section-fa2fda83-c99e-417a-8f36-df966d53fc7f' class='xr-section-summary' >Coordinates: <span>(7)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>i_interval</span></div><div class='xr-var-dims'>(i_interval)</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>1 2 3 4</div><input id='attrs-05b3da1b-4dbc-4156-9810-fc5c2536ae1b' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-05b3da1b-4dbc-4156-9810-fc5c2536ae1b' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-4750df8e-ff1d-49cf-8c3a-73e1781348ff' class='xr-var-data-in' type='checkbox'><label for='data-4750df8e-ff1d-49cf-8c3a-73e1781348ff' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([1, 2, 3, 4], dtype=int64)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>latitude</span></div><div class='xr-var-dims'>(latitude)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>47.5 42.5 37.5 32.5 27.5</div><input id='attrs-5dc96415-86e8-47db-83c9-2ba4a1c1daa6' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-5dc96415-86e8-47db-83c9-2ba4a1c1daa6' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-2edfc74c-d2b8-42bd-a888-fb5bc152816c' class='xr-var-data-in' type='checkbox'><label for='data-2edfc74c-d2b8-42bd-a888-fb5bc152816c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([47.5, 42.5, 37.5, 32.5, 27.5])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>longitude</span></div><div class='xr-var-dims'>(longitude)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>177.5 182.5 187.5 ... 232.5 237.5</div><input id='attrs-eb1cc3e1-d454-4e45-8b8e-147c60eab798' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-eb1cc3e1-d454-4e45-8b8e-147c60eab798' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-6243d329-5917-4487-90b6-680c4621ee68' class='xr-var-data-in' type='checkbox'><label for='data-6243d329-5917-4487-90b6-680c4621ee68' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([177.5, 182.5, 187.5, 192.5, 197.5, 202.5, 207.5, 212.5, 217.5, 222.5,\n",
+ " 227.5, 232.5, 237.5])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>area</span></div><div class='xr-var-dims'>(latitude)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>3.34e+06 3.645e+06 ... 4.385e+06</div><input id='attrs-61c0ee69-fbcc-47fe-8498-3f24bf3a405a' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-61c0ee69-fbcc-47fe-8498-3f24bf3a405a' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-00f507f0-341a-4c02-8721-40b9b0ab92f8' class='xr-var-data-in' type='checkbox'><label for='data-00f507f0-341a-4c02-8721-40b9b0ab92f8' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([3339800.84283772, 3644753.05166713, 3921966.48901128,\n",
+ " 4169331.39322594, 4384965.16802703])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>tfreq</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>5</div><input id='attrs-8c0f5aac-772d-4c8e-8e28-d05843c168d0' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-8c0f5aac-772d-4c8e-8e28-d05843c168d0' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-98695b91-dd7e-401b-9167-a67d74ab8e62' class='xr-var-data-in' type='checkbox'><label for='data-98695b91-dd7e-401b-9167-a67d74ab8e62' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array(5, dtype=int64)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>n_clusters</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>6</div><input id='attrs-ccf5d767-d518-4df4-8e1b-47e31111af9c' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-ccf5d767-d518-4df4-8e1b-47e31111af9c' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-e11d594d-5e70-4bfb-b766-84db0639c9db' class='xr-var-data-in' type='checkbox'><label for='data-e11d594d-5e70-4bfb-b766-84db0639c9db' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array(6, dtype=int64)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>cluster</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>3</div><input id='attrs-56288bf7-23ee-4a56-a121-e561a5fb98f1' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-56288bf7-23ee-4a56-a121-e561a5fb98f1' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-19ac81fa-703f-4610-80e3-f932c99d5df1' class='xr-var-data-in' type='checkbox'><label for='data-19ac81fa-703f-4610-80e3-f932c99d5df1' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array(3, dtype=int64)</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-60650f8e-73b5-4cda-adda-8dc4aed5eb47' class='xr-section-summary-in' type='checkbox' disabled ><label for='section-60650f8e-73b5-4cda-adda-8dc4aed5eb47' class='xr-section-summary' title='Expand/collapse section'>Attributes: <span>(0)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><dl class='xr-attrs'></dl></div></li></ul></div></div>"
+ ],
"text/plain": [
- "<matplotlib.collections.QuadMesh at 0x1c0c3f197b0>"
+ "<xarray.DataArray (latitude: 5, longitude: 13, i_interval: 4)>\n",
+ "0.01618 -0.2187 -0.2194 -0.2663 0.02414 ... -0.3984 -0.38 -0.3063 -0.1126\n",
+ "Coordinates:\n",
+ " * i_interval (i_interval) int64 1 2 3 4\n",
+ " * latitude (latitude) float64 47.5 42.5 37.5 32.5 27.5\n",
+ " * longitude (longitude) float64 177.5 182.5 187.5 ... 227.5 232.5 237.5\n",
+ " area (latitude) float64 3.34e+06 3.645e+06 ... 4.169e+06 4.385e+06\n",
+ " tfreq int64 5\n",
+ " n_clusters int64 6\n",
+ " cluster int64 3"
]
},
- "execution_count": 7,
+ "execution_count": 18,
"metadata": {},
"output_type": "execute_result"
- },
- {
- "data": {
- "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXYAAAEWCAYAAAByqrw/AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAAsTAAALEwEAmpwYAAAns0lEQVR4nO3de5wcZZ3v8c93BsI1ECAYAomAElRARIygK4JHQAGVsMcLghdY8WSR5RzWK0F8sYji4mXFdRdXsnhhFURE0Yjcr165hKvciYCSEMEgdxBI8j1/VA10Oj3TPTPV0z2d7/v1qtdUVT/91K9rZn791FNVT8k2ERHRO/o6HUBERFQriT0ioscksUdE9Jgk9oiIHpPEHhHRY5LYIyJ6TNcldkm3SHpTkzKflnTK2EQ0OpIul/ThTscxFElrSfq5pEcl/ajT8YwHkr4r6fOdjmO8kvQmSQs7HUev6rrEbntb25c3KfMF2y0lS0nHSvp+JcF1CUn/S9JlZSK+d5jvPVjSr+tWvwuYAmxk+91VxVm18kvyb5KeKKc7Oh3TaIyn5CbpCEn3SHpS0m2Stu50TDG4rkvs3UbSap2OoYEngW8Dn6yovs2BO20vbfRil+2Dw22vW04v63QwnTRWv5fyiPMQ4G3AusDbgSVjse0Yma5L7JLulbRHkzLPt8IlbSHJkg6S9CdJSyQdXb62F/BpYP+yhXdjuX59Sd+StFjSIkmfl9RfvnawpN9IOlHSQ8DnJD0iabua7W8s6WlJL5K0gaRzJP1F0sPl/LQ27R4AbF9t+3vA3cN5n6RXAN8EXl/uj0ckfRY4hhf20SEN9sGxktaQ9JVyHz8g6ZuS1qqp+5Pl/rxf0ofK38lWVX7u0Shb+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t/J8VDbVVT/ugyxjsor+4Zgxh3oehmuQm4oZz2ATYCLqH4crwY2LBT+3KIGP++3K/PAA8AF3TpvlxA0Qc8sO6bnYpziBh/TDGm003AzylOqHbV77uuzL28cFVMR/6/Oz1lSIGIiB6zKnXFRESsEpLYIyJ6TBJ7RESPSWKPiOgxSewRET0miT3aStITbahzX0lzyvn9JG0zgjouV92ojxG9Iok9xh3b82yfUC7uRzECYUSUkthjTJR3/n1Z0s0qxpvfv1z/prL1fJaKcclPK+8uRNI+5bpryzG1zynXHyzpPyX9HbAvxeBuN0h6aW1LXNLk8hZzJK0l6QxJt0k6G1irJra3qBgH/zpJPyrHIYkYt9r5MOuIWv8b2AF4FTAZuEbSwBDFrwa2pRj24TfAGyTNB04GdrV9j6Qf1Fdo+7eS5gHn2D4LoPxOaOQjwFO2XyFpe+C6svxkiuEb9rD9pKQjgY8Bx1XwmSM6Iok9xsouwA9sL6MYROwK4LXAY8DVthcCSLoB2AJ4ArjbxVjkUAzBMHsU298V+DqA7Zsk3VSufx1FV85vyi+FCcDvRrGdiI5LYo9u8EzN/DJG93e5lBe6GNdsobyAi2wfMIptRnSV9LHHWPkVsL+kfkkbU7Sghxqt8A7gJeXDFAD2H6Tc4xRj1w+4F3hNOf+umvW/BA4EkLQdsH25/kqKrp+tytfWkbR1Kx8oolslscdYOZtiRL4bgUuBT7kYVrUh208DhwHnlw8eeRx4tEHRM4BPSrpe0kspno71EUnXU/TlD/gvYF1Jt1H0n19bbucvwMHAD8rumd8BLx/NB43otIzuGF1L0rq2nyivkjkJuMv2iZ2OK6LbpcUe3ez/lCdTb6F4APnJnQ0nYnxIiz0iosekxR4R0WOS2CMiekwSe0REj0lij4joMUnsERE95v8D1NwfwBbM8aAAAAAASUVORK5CYII=",
- "text/plain": [
- "<Figure size 432x288 with 2 Axes>"
- ]
- },
- "metadata": {
- "needs_background": "light"
- },
- "output_type": "display_data"
}
],
"source": [
- "# visualize correlation map after RGDR().fit(precursor_field, target_timeseries)\n",
- "rgdr.corr_map[0].plot()"
+ "# View the contents of the corr_map DataArray:\n",
+ "rgdr.corr_map"
]
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
- "<matplotlib.collections.QuadMesh at 0x1c0c3e0e620>"
+ "<matplotlib.collections.QuadMesh at 0x1a068ef16f0>"
]
},
- "execution_count": 8,
+ "execution_count": 27,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
- "image/png": "iVBORw0KGgoAAAANSUhEUgAAAW4AAAEWCAYAAABG030jAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAAsTAAALEwEAmpwYAAAic0lEQVR4nO3deZwcVb338c83AYRAIEIAA4kGWVRANhHcrnARFRABH3HBjSjPjcvFBzckiC9kEa/bFfVefCQqiAoiIGhENpVFL7IlECJJWAKEJUQwQCAsZpn87h/nDCmanumeSdV01+T7fr3qNV3Vp0/9umbmV6dOnapSRGBmZvUxotMBmJnZwDhxm5nVjBO3mVnNOHGbmdWME7eZWc04cZuZ1UzXJW5JsyXt3aLMlyT9eGgiWj2Srpb0fzsdR38krSfpd5KekHR+p+OpA0k/lfTVTsdRV5L2lvRgp+Ooq65L3BGxQ0Rc3aLM1yKirWQo6QRJvygluC4h6V8lXZUT7fwBfnaSpP9pWHwosDmwSUS8p6w4y5Z3gv+U9FSe7uh0TKujTslL0lGS7pX0tKS5krbrdExrsq5L3N1G0lqdjqGJp4EzgKNLqu9lwJ0RsaLZm122DY6MiA3y9IpOB9NJQ/V7yUeMRwDvADYADgQWDcW6rbmuS9yS5kvat0WZ51rRkiZKCkmHS7pf0iJJx+X39gO+BLwvt9Buzcs3kvQTSQslLZD0VUkj83uTJF0r6VRJjwInS1osacfC+jeV9KykzSS9WNLFkv4h6fH8enxFmweAiLgxIn4O3DOQz0l6FfBD4PV5eyyWdCJ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U3A9hRP9kRE9IvEsOiKtGxFREREzKG0bEVERETMoVS2IiIiIuZQKlsRERERcyiVrYiIiIg5lMpWRERExBxKZSsiIiJiDv1/IiIGryeuimkAAAAASUVORK5CYII=",
"text/plain": [
- "<Figure size 432x288 with 2 Axes>"
+ "<Figure size 720x216 with 4 Axes>"
]
},
"metadata": {
@@ -694,30 +1133,32 @@
}
],
"source": [
- "# visualize p-values map\n",
- "rgdr.pval_map[0].plot()"
+ "fig, (ax1, ax2) = plt.subplots(figsize=(10, 3), ncols=2)\n",
+ "\n",
+ "# Visualize correlation map after RGDR().fit(precursor_field, target_timeseries)\n",
+ "rgdr.corr_map.sel(i_interval=1).plot(ax=ax1)\n",
+ "\n",
+ "# Visualize p-values map\n",
+ "rgdr.pval_map.sel(i_interval=1).plot(ax=ax2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The cluster maps can also be visualized. Note that clusters can differ between lags."
]
},
{
"cell_type": "code",
- "execution_count": 9,
+ "execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
+ "image/png": "iVBORw0KGgoAAAANSUhEUgAABCUAAACqCAYAAACaofWMAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAAsTAAALEwEAmpwYAAAsa0lEQVR4nO3deZglZX33//dnmAFUQFAQkSW4KxpFHJcnaqLGfUWfuBCjEheixkvQxD1XXKJ5YhKFEJPoPG644RqiPxQVI7g9Ksq+aVxABUFEQXEDZub7+6Oq5XTRy+npPkt1v1/XVddU1anlvuuc8+npu++6K1WFJEmSJEnSuK2bdAEkSZIkSdLaZKOEJEmSJEmaCBslJEmSJEnSRNgoIUmSJEmSJsJGCUmSJEmSNBE2SkiSJEmSpInoVaNEknOT3H+RbV6R5G3jKdHyJDk5ybMmXQ7NzfenH8wFjZPvTz+YCxon359+MBc0TkkuTPKgSZejL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JN5O8L0na1x7Rrjs1ydFJjm/XH5rkzUn+AHgM8E9Jzkhy68GWyyS7J7mwnb9Bkg8kOT/JccANBsr2kCRfSXJakg8n2Wm8V0dam8wFSV3mgqQuc0HTav2kC6AlezxwIHBXYHfg60m+0L52N+BOwI+ALwP3SfIN4K3AH1bVBUmO7R6wqv5fko8Dx1fVRwDaHJrLc4FfV9Udk9wFOK3dfnfgb4AHVdWvkrwUeBHw2hWos6SFmQuSuswFSV3mgqaSjRL9c1/g2KraAvw4yeeBewC/AE6pqosAkpwB7A/8EvheVV3Q7n8scNgyzv+HwNEAVXVWkrPa9fem6bb15TaItge+sozzSBqeuSCpy1yQ1GUuaCrZKLG6XD0wv4Xlvb+bue72nh2H2D7AiVV1yDLOKWnlmQuSuswFSV3mgibGMSX654vAk5Jsl2QPmhbHUxbY/lvArZLs3y4/aZ7trgJ2Hli+ELh7O/8nA+u/APwpQJI7A3dp13+VppvXbdrXbpTkdsNUSNKymQuSuswFSV3mgqaSjRL9cxxwFnAm8DngJVV16XwbV9VvgOcBn0pyKk1o/HyOTT8AvDjJ6UluDfwz8Nwkp9PcczbjP4CdkpxPc5/Xqe15fgIcChzbdsX6CnCH5VRU0tDMBUld5oKkLnNBUylVNekyaMSS7FRVv2xH0f034NtVdeSkyyVpcswFSV3mgqQuc0HjYE+JteHZ7YA15wI3phlFV9LaZi5I6jIXJHWZCxo5e0pIkiRJkqSJsKeEJEmSJEmaCBslJEmSJEnSRNgoIUmSJEmSJsJGCUmSJEmSNBE2SkiSJEmSpImwUUKSJEmSJE3E/w/hh2d8pEaHnQAAAABJRU5ErkJggg==",
"text/plain": [
- "<matplotlib.collections.QuadMesh at 0x1c0c298fdc0>"
- ]
- },
- "execution_count": 9,
- "metadata": {},
- "output_type": "execute_result"
- },
- {
- "data": {
- "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYUAAAEWCAYAAACJ0YulAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMi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kqEFDT77UAAAAASUVORK5CYII=",
- "text/plain": [
- "<Figure size 432x288 with 2 Axes>"
+ "<Figure size 1296x144 with 8 Axes>"
]
},
"metadata": {
@@ -727,11 +1168,22 @@
}
],
"source": [
- "# visualize clusters\n",
"from s2spy.rgdr.utils import cluster_labels_to_ints\n",
"cluster_map = cluster_labels_to_ints(rgdr.cluster_map.copy())\n",
- "cluster_map.cluster_labels[0].plot()"
+ "\n",
+ "fig, axes = plt.subplots(figsize=(18, 2), ncols=4)\n",
+ "\n",
+ "# Loop through lag 1 -> 4\n",
+ "for i, ax in zip((1, 2, 3, 4), axes):\n",
+ " cluster_map.cluster_labels.sel(i_interval=i).plot(ax=ax, cmap='RdYlBu', vmin=-2, vmax=2)"
]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
}
],
"metadata": {
diff --git a/s2spy/rgdr/rgdr.py b/s2spy/rgdr/rgdr.py
index 239f73c..605add3 100644
--- a/s2spy/rgdr/rgdr.py
+++ b/s2spy/rgdr/rgdr.py
@@ -392,7 +392,7 @@ class RGDR:
corr, p_val = self.get_correlation(precursor, timeseries)
return masked_spherical_dbscan(precursor, corr, p_val, self._dbscan_params)
- def plot_correlation( # pylint: disable=too-many-arguments
+ def preview_correlation( # pylint: disable=too-many-arguments
self,
precursor: xr.DataArray,
timeseries: xr.DataArray,
@@ -444,7 +444,7 @@ class RGDR:
return [plot1, plot2]
- def plot_clusters(
+ def preview_clusters(
self,
precursor: xr.DataArray,
timeseries: xr.DataArray,
|
AI4S2S__s2spy-77
|
[
{
"changes": {
"added_entities": [
"s2spy/_base_calendar.py:BaseCalendar.set_max_lag"
],
"added_modules": null,
"edited_entities": [
"s2spy/_base_calendar.py:BaseCalendar.__init__",
"s2spy/_base_calendar.py:BaseCalendar._get_nintervals",
"s2spy/_base_calendar.py:BaseCalendar._get_skip_nyears",
"s2spy/_base_calendar.py:BaseCalendar.map_years",
"s2spy/_base_calendar.py:BaseCalendar._set_year_range_from_timestamps"
],
"edited_modules": [
"s2spy/_base_calendar.py:BaseCalendar"
]
},
"file": "s2spy/_base_calendar.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"s2spy/_resample.py:resample_pandas",
"s2spy/_resample.py:resample"
],
"edited_modules": [
"s2spy/_resample.py:resample_pandas",
"s2spy/_resample.py:resample"
]
},
"file": "s2spy/_resample.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"s2spy/time.py:AdventCalendar.__init__",
"s2spy/time.py:MonthlyCalendar.__init__",
"s2spy/time.py:MonthlyCalendar._get_nintervals",
"s2spy/time.py:MonthlyCalendar._get_skip_nyears",
"s2spy/time.py:WeeklyCalendar.__init__"
],
"edited_modules": [
"s2spy/time.py:AdventCalendar",
"s2spy/time.py:MonthlyCalendar",
"s2spy/time.py:WeeklyCalendar"
]
},
"file": "s2spy/time.py"
},
{
"changes": {
"added_entities": [
"s2spy/utils.py:check_empty_intervals",
"s2spy/utils.py:check_input_frequency"
],
"added_modules": [
"s2spy/utils.py:check_empty_intervals",
"s2spy/utils.py:check_input_frequency"
],
"edited_entities": null,
"edited_modules": null
},
"file": "s2spy/utils.py"
}
] |
AI4S2S/s2spy
|
c254e11f1a64aaa52593e3848b71207421a16c61
|
Dealing with mismatch between calendar map and data time extent
PR #60 changes resample so that it takes a mapped calendar and resamples the input data based on those intervals.
However, this will require some extra checks and data handling to prevent user error;
- [ ] Add check to see if the data can fully cover the calendar, and warn the user if it cannot.
- [ ] Ensure that if Pandas data is insufficient to cover the calendar, NaNs will be used for the empty intervals
- [ ] Add tests to ensure that both the warning & the NaN filling goes correctly
The second task already works for the xarray implementation, but not yet for Pandas data.
Related to #26
|
diff --git a/notebooks/tutorial_time.ipynb b/notebooks/tutorial_time.ipynb
index 149fa99..4cdcf45 100644
--- a/notebooks/tutorial_time.ipynb
+++ b/notebooks/tutorial_time.ipynb
@@ -27,7 +27,7 @@
"name": "stdout",
"output_type": "stream",
"text": [
- "AdventCalendar(month=12, day=31, freq=7d, n_targets=1, max_lag=None)\n"
+ "AdventCalendar(month=12, day=31, freq=7d, n_targets=1)\n"
]
}
],
@@ -52,7 +52,7 @@
{
"data": {
"text/plain": [
- "AdventCalendar(month=11, day=30, freq=90d, n_targets=1, max_lag=None)"
+ "AdventCalendar(month=11, day=30, freq=90d, n_targets=1)"
]
},
"execution_count": 3,
@@ -284,7 +284,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Map the calendar to the input data."
+ "Set the maximum lag"
]
},
{
@@ -316,14 +316,12 @@
" <th>(target) 0</th>\n",
" <th>1</th>\n",
" <th>2</th>\n",
- " <th>3</th>\n",
" </tr>\n",
" <tr>\n",
" <th>anchor_year</th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
- " <th></th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
@@ -332,21 +330,18 @@
" <td>(2022-09-01, 2022-11-30]</td>\n",
" <td>(2022-06-03, 2022-09-01]</td>\n",
" <td>(2022-03-05, 2022-06-03]</td>\n",
- " <td>(2021-12-05, 2022-03-05]</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2021</th>\n",
" <td>(2021-09-01, 2021-11-30]</td>\n",
" <td>(2021-06-03, 2021-09-01]</td>\n",
" <td>(2021-03-05, 2021-06-03]</td>\n",
- " <td>(2020-12-05, 2021-03-05]</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2020</th>\n",
" <td>(2020-09-01, 2020-11-30]</td>\n",
" <td>(2020-06-03, 2020-09-01]</td>\n",
" <td>(2020-03-05, 2020-06-03]</td>\n",
- " <td>(2019-12-06, 2020-03-05]</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
@@ -359,11 +354,11 @@
"2021 (2021-09-01, 2021-11-30] (2021-06-03, 2021-09-01] \n",
"2020 (2020-09-01, 2020-11-30] (2020-06-03, 2020-09-01] \n",
"\n",
- "i_interval 2 3 \n",
- "anchor_year \n",
- "2022 (2022-03-05, 2022-06-03] (2021-12-05, 2022-03-05] \n",
- "2021 (2021-03-05, 2021-06-03] (2020-12-05, 2021-03-05] \n",
- "2020 (2020-03-05, 2020-06-03] (2019-12-06, 2020-03-05] "
+ "i_interval 2 \n",
+ "anchor_year \n",
+ "2022 (2022-03-05, 2022-06-03] \n",
+ "2021 (2021-03-05, 2021-06-03] \n",
+ "2020 (2020-03-05, 2020-06-03] "
]
},
"execution_count": 7,
@@ -371,6 +366,105 @@
"output_type": "execute_result"
}
],
+ "source": [
+ "calendar.set_max_lag(2)\n",
+ "calendar.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Map the calendar to the input data."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<div>\n",
+ "<style scoped>\n",
+ " .dataframe tbody tr th:only-of-type {\n",
+ " vertical-align: middle;\n",
+ " }\n",
+ "\n",
+ " .dataframe tbody tr th {\n",
+ " vertical-align: top;\n",
+ " }\n",
+ "\n",
+ " .dataframe thead th {\n",
+ " text-align: right;\n",
+ " }\n",
+ "</style>\n",
+ "<table border=\"1\" class=\"dataframe\">\n",
+ " <thead>\n",
+ " <tr style=\"text-align: right;\">\n",
+ " <th>i_interval</th>\n",
+ " <th>(target) 0</th>\n",
+ " <th>1</th>\n",
+ " <th>2</th>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>anchor_year</th>\n",
+ " <th></th>\n",
+ " <th></th>\n",
+ " <th></th>\n",
+ " </tr>\n",
+ " </thead>\n",
+ " <tbody>\n",
+ " <tr>\n",
+ " <th>2021</th>\n",
+ " <td>(2021-09-01, 2021-11-30]</td>\n",
+ " <td>(2021-06-03, 2021-09-01]</td>\n",
+ " <td>(2021-03-05, 2021-06-03]</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2020</th>\n",
+ " <td>(2020-09-01, 2020-11-30]</td>\n",
+ " <td>(2020-06-03, 2020-09-01]</td>\n",
+ " <td>(2020-03-05, 2020-06-03]</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2019</th>\n",
+ " <td>(2019-09-01, 2019-11-30]</td>\n",
+ " <td>(2019-06-03, 2019-09-01]</td>\n",
+ " <td>(2019-03-05, 2019-06-03]</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2018</th>\n",
+ " <td>(2018-09-01, 2018-11-30]</td>\n",
+ " <td>(2018-06-03, 2018-09-01]</td>\n",
+ " <td>(2018-03-05, 2018-06-03]</td>\n",
+ " </tr>\n",
+ " </tbody>\n",
+ "</table>\n",
+ "</div>"
+ ],
+ "text/plain": [
+ "i_interval (target) 0 1 \\\n",
+ "anchor_year \n",
+ "2021 (2021-09-01, 2021-11-30] (2021-06-03, 2021-09-01] \n",
+ "2020 (2020-09-01, 2020-11-30] (2020-06-03, 2020-09-01] \n",
+ "2019 (2019-09-01, 2019-11-30] (2019-06-03, 2019-09-01] \n",
+ "2018 (2018-09-01, 2018-11-30] (2018-06-03, 2018-09-01] \n",
+ "\n",
+ "i_interval 2 \n",
+ "anchor_year \n",
+ "2021 (2021-03-05, 2021-06-03] \n",
+ "2020 (2020-03-05, 2020-06-03] \n",
+ "2019 (2019-03-05, 2019-06-03] \n",
+ "2018 (2018-03-05, 2018-06-03] "
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"# create dummy data for testing\n",
"time_index = pd.date_range('20171110', '20211211', freq='10d')\n",
diff --git a/s2spy/_base_calendar.py b/s2spy/_base_calendar.py
index 4f1f880..27e5896 100644
--- a/s2spy/_base_calendar.py
+++ b/s2spy/_base_calendar.py
@@ -23,13 +23,20 @@ class BaseCalendar(ABC):
_mapping = None
@abstractmethod
- def __init__(self, anchor, freq, n_targets: int = 1, max_lag: int = None):
- """For initializing calendars, the following four variables will be required."""
+ def __init__(
+ self,
+ anchor,
+ freq,
+ n_targets: int = 1,
+ ):
+ """For initializing calendars, the following five variables will be required."""
self.n_targets = n_targets
- self.max_lag = max_lag
self.anchor = anchor
self.freq = freq
+ self._max_lag = 0
+ self._allow_overlap = False
+
@abstractmethod
def _get_anchor(self, year: int) -> pd.Timestamp:
"""Method to generate an anchor timestamp for your specific calendar.
@@ -46,6 +53,31 @@ class BaseCalendar(ABC):
"""
return pd.Timestamp()
+ def set_max_lag(self, max_lag: int, allow_overlap: bool = False) -> None:
+ """Set the maximum lag of a calendar.
+
+ Sets the maximum number of lag periods after the target period. If `0`,
+ the maximum lag will be determined by how many fit in each anchor year.
+ If a maximum lag is provided, the intervals can either only cover part
+ of the year, or extend over multiple years. In case of a large max_lag
+ number where the intervals extend over multiple years, anchor years will
+ be skipped to avoid overlapping intervals. To allow overlapping
+ intervals, use the `allow_overlap` kwarg.
+
+ Args:
+ max_lag: Maximum number of lag periods after the target period.
+ allow_overlap: Allows intervals to overlap between anchor years, if the
+ max_lag is set to a high enough number that intervals extend over
+ multiple years. `False` by default, to avoid train/test information
+ leakage.
+ """
+ if (max_lag < 0) or (max_lag % 1 > 0):
+ raise ValueError("Max lag should be an integer with a value of 0 or greater"
+ f", not {max_lag} of type {type(max_lag)}.")
+
+ self._max_lag = max_lag
+ self._allow_overlap = allow_overlap
+
def _map_year(self, year: int) -> pd.Series:
"""Internal routine to return a concrete IntervalIndex for the given year.
@@ -81,7 +113,7 @@ class BaseCalendar(ABC):
"""
periods_per_year = pd.Timedelta("365days") / pd.to_timedelta(self.freq)
return (
- (self.max_lag + self.n_targets) if self.max_lag else int(periods_per_year)
+ (self._max_lag + self.n_targets) if self._max_lag > 0 else int(periods_per_year)
)
def _get_skip_nyears(self) -> int:
@@ -96,9 +128,9 @@ class BaseCalendar(ABC):
periods_per_year = pd.Timedelta("365days") / pd.to_timedelta(self.freq)
return (
- (np.ceil(nintervals / periods_per_year).astype(int) - 1)
- if self.max_lag
- else 0
+ 0
+ if self._max_lag > 0 and self._allow_overlap
+ else int(np.ceil(nintervals / periods_per_year).astype(int) - 1)
)
def map_years(self, start: int, end: int):
@@ -114,6 +146,9 @@ class BaseCalendar(ABC):
Returns:
The calendar mapped to the input start and end year.
"""
+ if start > end:
+ raise ValueError("The start year cannot be greater than the end year")
+
self._first_year = start
self._last_year = end
self._mapping = "years"
@@ -151,21 +186,21 @@ class BaseCalendar(ABC):
return self
def _set_year_range_from_timestamps(self):
- map_first_year = self._first_timestamp.year
- map_last_year = self._last_timestamp.year
+ min_year = self._first_timestamp.year
+ max_year = self._last_timestamp.year
# ensure that the input data could always cover the advent calendar
# last date check
- if self._map_year(map_last_year).iloc[0].right > self._last_timestamp:
- map_last_year -= 1
+ if self._map_year(max_year).iloc[0].right > self._last_timestamp:
+ max_year -= 1
# first date check
- if self._map_year(map_first_year).iloc[-1].left < self._first_timestamp:
- map_first_year += 1
+ while self._map_year(min_year).iloc[-1].right <= self._first_timestamp:
+ min_year += 1
# map year(s) and generate year realized advent calendar
- if map_last_year >= map_first_year:
- self._first_year = map_first_year
- self._last_year = map_last_year
+ if max_year >= min_year:
+ self._first_year = min_year
+ self._last_year = max_year
else:
raise ValueError(
"The input data could not cover the target advent calendar."
diff --git a/s2spy/_resample.py b/s2spy/_resample.py
index b61130f..646d9b5 100644
--- a/s2spy/_resample.py
+++ b/s2spy/_resample.py
@@ -1,4 +1,3 @@
-import warnings
from typing import Union
import numpy as np
import pandas as pd
@@ -97,8 +96,8 @@ def resample_pandas(
interval_groups = interval_index.get_indexer(input_data.index)
interval_means = input_data.groupby(interval_groups).mean()
- # drop the -1 index, as it represents data outside of all intervals
- interval_means = interval_means.loc[0:]
+ # Reindex the intervals. Empty intervals will contain NaN values.
+ interval_means = interval_means.reindex(np.arange(len(interval_index)))
if isinstance(input_data, pd.DataFrame):
for name in input_data.keys():
@@ -220,24 +219,14 @@ def resample(
raise ValueError("Generate a calendar map before calling resample")
utils.check_timeseries(input_data)
+ utils.check_input_frequency(mapped_calendar, input_data)
if isinstance(input_data, PandasData):
- # raise a warning for upscaling
- # target frequency must be larger than the (absolute) input frequency
- if input_data.index.freq:
- input_freq = input_data.index.freq
- input_freq = input_freq if input_freq.n > 0 else -input_freq
- if pd.Timedelta(mapped_calendar.freq) < input_freq:
- warnings.warn(
- """Target frequency is smaller than the original frequency.
- The resampled data will contain NaN values, as there is no data
- available within all intervals."""
- )
-
resampled_data = resample_pandas(mapped_calendar, input_data)
-
else:
resampled_data = resample_xarray(mapped_calendar, input_data)
+ utils.check_empty_intervals(resampled_data)
+
# mark target periods before returning the resampled data
return mark_target_period(mapped_calendar, resampled_data)
diff --git a/s2spy/time.py b/s2spy/time.py
index 288c4d5..667f611 100644
--- a/s2spy/time.py
+++ b/s2spy/time.py
@@ -14,7 +14,7 @@ Example:
>>> # Countdown the weeks until New Year's Eve
>>> calendar = s2spy.time.AdventCalendar(anchor=(12, 31), freq="7d")
>>> calendar
- AdventCalendar(month=12, day=31, freq=7d, n_targets=1, max_lag=None)
+ AdventCalendar(month=12, day=31, freq=7d, n_targets=1)
>>> # Get the 180-day periods leading up to New Year's eve for the year 2020
>>> calendar = s2spy.time.AdventCalendar(anchor=(12, 31), freq='180d')
@@ -49,7 +49,6 @@ Example:
"""
import calendar as pycalendar
import re
-from typing import Optional
from typing import Tuple
import numpy as np
import pandas as pd
@@ -75,7 +74,6 @@ class AdventCalendar(BaseCalendar):
anchor: Tuple[int, int] = (11, 30),
freq: str = "7d",
n_targets: int = 1,
- max_lag: Optional[int] = None,
) -> None:
"""Instantiate a basic calendar with minimal configuration.
@@ -88,12 +86,6 @@ class AdventCalendar(BaseCalendar):
of the calendar. It will countdown until this date.
freq: Frequency of the calendar.
n_targets: integer specifying the number of target intervals in a period.
- max_lag: Maximum number of lag periods after the target period. If `None`,
- the maximum lag will be determined by how many fit in each anchor year.
- If a maximum lag is provided, the intervals can either only cover part
- of the year, or extend over multiple years. In case of a large max_lag
- number where the intervals extend over multiple years, anchor years will
- be skipped to avoid overlapping intervals.
Example:
Instantiate a calendar counting down the weeks until new-year's
@@ -102,7 +94,7 @@ class AdventCalendar(BaseCalendar):
>>> import s2spy.time
>>> calendar = s2spy.time.AdventCalendar(anchor=(12, 31), freq="7d")
>>> calendar
- AdventCalendar(month=12, day=31, freq=7d, n_targets=1, max_lag=None)
+ AdventCalendar(month=12, day=31, freq=7d, n_targets=1)
"""
if not re.fullmatch(r"\d*d", freq):
@@ -111,7 +103,9 @@ class AdventCalendar(BaseCalendar):
self.day = anchor[1]
self.freq = freq
self.n_targets = n_targets
- self.max_lag = max_lag
+
+ self._max_lag:int = 0
+ self._allow_overlap: bool = False
def _get_anchor(self, year: int) -> pd.Timestamp:
"""Generates a timestamp for the end of interval 0 in year.
@@ -133,7 +127,6 @@ class MonthlyCalendar(BaseCalendar):
anchor: str = "Dec",
freq: str = "1M",
n_targets: int = 1,
- max_lag: Optional[int] = None,
) -> None:
"""Instantiate a basic monthly calendar with minimal configuration.
@@ -146,12 +139,6 @@ class MonthlyCalendar(BaseCalendar):
of the calendar. It will countdown up to this month.
freq: Frequency of the calendar, in the form '1M', '2M', etc.
n_targets: integer specifying the number of target intervals in a period.
- max_lag: Maximum number of lag periods after the target period. If `None`,
- the maximum lag will be determined by how many fit in each anchor year.
- If a maximum lag is provided, the intervals can either only cover part
- of the year, or extend over multiple years. In case of a large max_lag
- number where the intervals extend over multiple years, anchor years will
- be skipped to avoid overlapping intervals.
Example:
Instantiate a calendar counting down the quarters (3 month periods) until
@@ -160,15 +147,17 @@ class MonthlyCalendar(BaseCalendar):
>>> import s2spy.time
>>> calendar = s2spy.time.MonthlyCalendar(anchor='Dec', freq="3M")
>>> calendar
- MonthlyCalendar(month=12, freq=3M, n_targets=1, max_lag=None)
+ MonthlyCalendar(month=12, freq=3M, n_targets=1)
"""
if not re.fullmatch(r"\d*M", freq):
raise ValueError("Please input a frequency in the form of '2M'")
+
self.month = month_mapping_dict[anchor.upper()]
self.freq = freq
self.n_targets = n_targets
- self.max_lag = max_lag
+ self._max_lag = 0
+ self._allow_overlap = False
def _get_anchor(self, year: int) -> pd.Timestamp:
"""Generates a timestamp for the end of interval 0 in year.
@@ -189,7 +178,7 @@ class MonthlyCalendar(BaseCalendar):
"""
periods_per_year = 12 / int(self.freq.replace("M", ""))
return (
- (self.max_lag + self.n_targets) if self.max_lag else int(periods_per_year)
+ (self._max_lag + self.n_targets) if self._max_lag > 0 else int(periods_per_year)
)
def _get_skip_nyears(self) -> int:
@@ -201,7 +190,11 @@ class MonthlyCalendar(BaseCalendar):
int: Number of years that need to be skipped.
"""
nmonths = int(self.freq.replace("M", ""))
- return (np.ceil(nmonths / 12) - 1) if self.max_lag else 0
+ return (
+ 0
+ if self._max_lag > 0 and self._allow_overlap
+ else int(np.ceil(nmonths / 12) - 1)
+ )
def _interval_as_month(self, interval):
"""Turns an interval with pandas Timestamp values to a formatted string.
@@ -239,7 +232,6 @@ class WeeklyCalendar(BaseCalendar):
anchor: int,
freq: str = "1W",
n_targets: int = 1,
- max_lag: Optional[int] = None,
) -> None:
"""Instantiate a basic week number calendar with minimal configuration.
@@ -254,12 +246,6 @@ class WeeklyCalendar(BaseCalendar):
It will countdown until this week.
freq: Frequency of the calendar, e.g. '2W'.
n_targets: integer specifying the number of target intervals in a period.
- max_lag: Maximum number of lag periods after the target period. If `None`,
- the maximum lag will be determined by how many fit in each anchor year.
- If a maximum lag is provided, the intervals can either only cover part
- of the year, or extend over multiple years. In case of a large max_lag
- number where the intervals extend over multiple years, anchor years will
- be skipped to avoid overlapping intervals.
Example:
Instantiate a calendar counting down the weeks until week number 40.
@@ -267,7 +253,7 @@ class WeeklyCalendar(BaseCalendar):
>>> import s2spy.time
>>> calendar = s2spy.time.WeeklyCalendar(anchor=40, freq="1W")
>>> calendar
- WeeklyCalendar(week=40, freq=1W, n_targets=1, max_lag=None)
+ WeeklyCalendar(week=40, freq=1W, n_targets=1)
"""
if not re.fullmatch(r"\d*W", freq):
@@ -276,7 +262,9 @@ class WeeklyCalendar(BaseCalendar):
self.week = anchor
self.freq = freq
self.n_targets = n_targets
- self.max_lag = max_lag
+
+ self._max_lag: int = 0
+ self._allow_overlap: bool = False
def _get_anchor(self, year: int) -> pd.Timestamp:
"""Generates a timestamp for the end of interval 0 in year.
diff --git a/s2spy/utils.py b/s2spy/utils.py
index 4f88764..e090f19 100644
--- a/s2spy/utils.py
+++ b/s2spy/utils.py
@@ -1,3 +1,7 @@
+import re
+import warnings
+from typing import Union
+import numpy as np
import pandas as pd
import xarray as xr
@@ -36,3 +40,63 @@ def check_time_dim_pandas(data) -> None:
"""Utility function to check if pandas data has an index with time data."""
if not isinstance(data.index, pd.DatetimeIndex):
raise ValueError("The input data does not have a datetime index.")
+
+
+def check_empty_intervals(data: Union[pd.DataFrame, xr.Dataset]) -> None:
+ """Utility to check for empty intervals in data.
+
+ Note: For the Dataset, all values within a certain interval, anchor_year combination
+ have to be NaN, to allow for, e.g., empty gridcells in a latitude/longitude grid.
+
+ Args:
+ data (Union[pd.DataFrame, xr.Dataset]): Data that should be checked for empty
+ intervals. Should be done after resampling the data.
+
+ Raises:
+ UserWarning: If the data is insufficient.
+
+ Returns:
+ None
+ """
+ if isinstance(data, pd.DataFrame) and not np.any(np.isnan(data.iloc[:, 3:])):
+ return None
+ if isinstance(data, xr.Dataset) and not any(
+ data[var].isnull().any(dim=["i_interval", "anchor_year"]).all()
+ for var in data.data_vars
+ ):
+ return None
+
+ warnings.warn(
+ "The input data could not fully cover the calendar's intervals. "
+ "Intervals without available data will contain NaN values."
+ )
+ return None
+
+
+def check_input_frequency(calendar, data):
+ """Checks the frequency of (input) data.
+
+ Note: Pandas and xarray have the builtin function `infer_freq`, but this function is
+ not robust enough for our purpose, so we have to manually infer the frequency if the
+ builtin one fails.
+ """
+ if isinstance(data, PandasData):
+ data_freq = pd.infer_freq(data.index)
+ if data_freq is None: # Manually infer the frequency
+ data_freq = np.min(data.index.values[1:] - data.index.values[:-1])
+ else:
+ data_freq = xr.infer_freq(data.time)
+ if data_freq is None: # Manually infer the frequency
+ data_freq = (data.time.values[1:] - data.time.values[:-1]).min()
+
+ if isinstance(data_freq, str):
+ data_freq.replace("-", "")
+ if not re.match(r'\d+\D', data_freq):
+ data_freq = '1' + data_freq
+
+ if pd.Timedelta(calendar.freq) < pd.Timedelta(data_freq):
+ warnings.warn(
+ """Target frequency is smaller than the original frequency.
+ The resampled data will contain NaN values, as there is no data
+ available within all intervals."""
+ )
|
AI4S2S__s2spy-83
|
[
{
"changes": {
"added_entities": [
"s2spy/rgdr/rgdr.py:RGDR.get_correlation",
"s2spy/rgdr/rgdr.py:RGDR.get_clusters",
"s2spy/rgdr/rgdr.py:RGDR.fit_transform"
],
"added_modules": null,
"edited_entities": [
"s2spy/rgdr/rgdr.py:masked_spherical_dbscan",
"s2spy/rgdr/rgdr.py:RGDR.__init__",
"s2spy/rgdr/rgdr.py:RGDR.plot_correlation",
"s2spy/rgdr/rgdr.py:RGDR.plot_clusters",
"s2spy/rgdr/rgdr.py:RGDR.fit"
],
"edited_modules": [
"s2spy/rgdr/rgdr.py:masked_spherical_dbscan",
"s2spy/rgdr/rgdr.py:RGDR"
]
},
"file": "s2spy/rgdr/rgdr.py"
}
] |
AI4S2S/s2spy
|
1bd615deba811a0b978e2c3abfad6c1de1be8851
|
Return correlation / p_values from RGDR
Currently the correlation and p_values are not accessible by the user. The user can only visualize the those values via RGDR built-in plot functions. The users may need to investigate/store these values in case they want to check the correlation of the precursor fields and target timeseries for all the `i_intervals`. So RGDR should return correlation and p_values.
|
diff --git a/notebooks/tutorial_RGDR.ipynb b/notebooks/tutorial_RGDR.ipynb
index 198ccea..29a7389 100644
--- a/notebooks/tutorial_RGDR.ipynb
+++ b/notebooks/tutorial_RGDR.ipynb
@@ -53,7 +53,7 @@
"target_timeseries = target_resampled.sel(cluster=3).ts.isel(i_interval=0)\n",
"precursor_field = field_resampled.sst.isel(i_interval=1)\n",
"\n",
- "rgdr = RGDR(target_timeseries, eps_km=600, alpha=0.05, min_area_km2=3000**2)"
+ "rgdr = RGDR(eps_km=600, alpha=0.05, min_area_km2=3000**2)"
]
},
{
@@ -83,7 +83,7 @@
],
"source": [
"fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 2))\n",
- "_ = rgdr.plot_correlation(precursor_field, ax1, ax2)"
+ "_ = rgdr.plot_correlation(precursor_field, target_timeseries, ax1, ax2)"
]
},
{
@@ -116,20 +116,17 @@
"source": [
"fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 2))\n",
"\n",
- "_ = rgdr.plot_clusters(precursor_field, ax=ax1)\n",
+ "_ = rgdr.plot_clusters(precursor_field, target_timeseries, ax=ax1)\n",
"\n",
- "_ = RGDR(target_timeseries,\n",
- " eps_km=600,\n",
- " alpha=0.05,\n",
- " min_area_km2=1000**2\n",
- " ).plot_clusters(precursor_field, ax=ax2)"
+ "_ = RGDR(min_area_km2=1000**2).plot_clusters(precursor_field, target_timeseries, ax=ax2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "With `.fit` the RGDR clustering can be fit to a precursor field. This will return the data reduced to clusters:"
+ "With `.fit` the RGDR clustering can be fit to a precursor field.\n",
+ "`.transform` can then be used to return the data reduced to clusters:"
]
},
{
@@ -171,6 +168,7 @@
"}\n",
"\n",
"html[theme=dark],\n",
+ "body[data-theme=dark],\n",
"body.vscode-dark {\n",
" --xr-font-color0: rgba(255, 255, 255, 1);\n",
" --xr-font-color2: rgba(255, 255, 255, 0.54);\n",
@@ -494,12 +492,14 @@
"</style><pre class='xr-text-repr-fallback'><xarray.DataArray 'sst' (cluster_labels: 3, anchor_year: 39)>\n",
"290.8 291.0 290.7 290.1 291.1 291.3 ... 299.0 299.5 298.9 298.9 299.2 298.2\n",
"Coordinates:\n",
+ " * anchor_year (anchor_year) int32 1980 1981 1982 1983 ... 2016 2017 2018\n",
+ " i_interval int64 1\n",
" index (anchor_year) int64 1 13 25 37 49 61 ... 409 421 433 445 457\n",
" interval (anchor_year) object (1980-07-02, 1980-08-01] ... (2018-0...\n",
- " * anchor_year (anchor_year) int64 1980 1981 1982 1983 ... 2016 2017 2018\n",
- " i_interval int64 1\n",
" target bool False\n",
- " * cluster_labels (cluster_labels) float64 -2.0 0.0 1.0</pre><div class='xr-wrap' style='display:none'><div class='xr-header'><div class='xr-obj-type'>xarray.DataArray</div><div class='xr-array-name'>'sst'</div><ul class='xr-dim-list'><li><span class='xr-has-index'>cluster_labels</span>: 3</li><li><span class='xr-has-index'>anchor_year</span>: 39</li></ul></div><ul class='xr-sections'><li class='xr-section-item'><div class='xr-array-wrap'><input id='section-57548d43-1b48-4abf-a765-2fa308c2d9ce' class='xr-array-in' type='checkbox' ><label for='section-57548d43-1b48-4abf-a765-2fa308c2d9ce' title='Show/hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-array-preview xr-preview'><span>290.8 291.0 290.7 290.1 291.1 291.3 ... 299.5 298.9 298.9 299.2 298.2</span></div><div class='xr-array-data'><pre>array([[290.79588914, 290.970545 , 290.71731703, 290.0762239 ,\n",
+ " * cluster_labels (cluster_labels) int32 -2 0 1\n",
+ " latitude (cluster_labels) float64 36.05 nan 29.44\n",
+ " longitude (cluster_labels) float64 223.9 nan 185.4</pre><div class='xr-wrap' style='display:none'><div class='xr-header'><div class='xr-obj-type'>xarray.DataArray</div><div class='xr-array-name'>'sst'</div><ul class='xr-dim-list'><li><span class='xr-has-index'>cluster_labels</span>: 3</li><li><span class='xr-has-index'>anchor_year</span>: 39</li></ul></div><ul class='xr-sections'><li class='xr-section-item'><div class='xr-array-wrap'><input id='section-f5bc8d25-bf34-4c88-9121-f7ab7fd5d804' class='xr-array-in' type='checkbox' ><label for='section-f5bc8d25-bf34-4c88-9121-f7ab7fd5d804' title='Show/hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-array-preview xr-preview'><span>290.8 291.0 290.7 290.1 291.1 291.3 ... 299.5 298.9 298.9 299.2 298.2</span></div><div class='xr-array-data'><pre>array([[290.79588914, 290.970545 , 290.71731703, 290.0762239 ,\n",
" 291.08960917, 291.31511491, 291.11538436, 290.26277142,\n",
" 290.80443321, 290.99960169, 291.53446464, 291.36075119,\n",
" 291.85483292, 291.09343404, 291.31408735, 291.41374784,\n",
@@ -528,10 +528,13 @@
" 298.88763028, 299.2529288 , 299.0168395 , 298.84020348,\n",
" 298.48441327, 299.30649003, 299.69018872, 299.65241405,\n",
" 299.320106 , 299.04325189, 299.48610574, 298.91044985,\n",
- " 298.89195415, 299.19568083, 298.21053747]])</pre></div></div></li><li class='xr-section-item'><input id='section-7b3a0711-0bee-4e8a-bff6-653d382b6cee' class='xr-section-summary-in' type='checkbox' checked><label for='section-7b3a0711-0bee-4e8a-bff6-653d382b6cee' class='xr-section-summary' >Coordinates: <span>(6)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span>index</span></div><div class='xr-var-dims'>(anchor_year)</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>1 13 25 37 49 ... 421 433 445 457</div><input id='attrs-67060b83-a064-4867-b21f-60b066184d18' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-67060b83-a064-4867-b21f-60b066184d18' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-2793a313-1fa1-4469-b925-db2c25e8422e' class='xr-var-data-in' type='checkbox'><label for='data-2793a313-1fa1-4469-b925-db2c25e8422e' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([ 1, 13, 25, 37, 49, 61, 73, 85, 97, 109, 121, 133, 145,\n",
+ " 298.89195415, 299.19568083, 298.21053747]])</pre></div></div></li><li class='xr-section-item'><input id='section-95b251ac-392b-4d4b-bf6e-b9f7afec9cb5' class='xr-section-summary-in' type='checkbox' checked><label for='section-95b251ac-392b-4d4b-bf6e-b9f7afec9cb5' class='xr-section-summary' >Coordinates: <span>(8)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><ul class='xr-var-list'><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>anchor_year</span></div><div class='xr-var-dims'>(anchor_year)</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>1980 1981 1982 ... 2016 2017 2018</div><input id='attrs-8dba64f4-e3d0-4ae4-96fa-6a0144a3cfc1' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-8dba64f4-e3d0-4ae4-96fa-6a0144a3cfc1' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-71816fcd-d623-4450-bd28-c276610ad0e4' class='xr-var-data-in' type='checkbox'><label for='data-71816fcd-d623-4450-bd28-c276610ad0e4' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991,\n",
+ " 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,\n",
+ " 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,\n",
+ " 2016, 2017, 2018])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>i_interval</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>1</div><input id='attrs-266c79b1-cd75-4fd9-a1a9-6e762b299ed2' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-266c79b1-cd75-4fd9-a1a9-6e762b299ed2' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-808c7c66-0d03-48c8-a094-5c5afae42b3c' class='xr-var-data-in' type='checkbox'><label for='data-808c7c66-0d03-48c8-a094-5c5afae42b3c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array(1, dtype=int64)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>index</span></div><div class='xr-var-dims'>(anchor_year)</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>1 13 25 37 49 ... 421 433 445 457</div><input id='attrs-d96ed652-a251-48e3-a9c9-c78621ce231e' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-d96ed652-a251-48e3-a9c9-c78621ce231e' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-a70f5ba4-8506-474a-81fb-d3e40861c04c' class='xr-var-data-in' type='checkbox'><label for='data-a70f5ba4-8506-474a-81fb-d3e40861c04c' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([ 1, 13, 25, 37, 49, 61, 73, 85, 97, 109, 121, 133, 145,\n",
" 157, 169, 181, 193, 205, 217, 229, 241, 253, 265, 277, 289, 301,\n",
" 313, 325, 337, 349, 361, 373, 385, 397, 409, 421, 433, 445, 457],\n",
- " dtype=int64)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>interval</span></div><div class='xr-var-dims'>(anchor_year)</div><div class='xr-var-dtype'>object</div><div class='xr-var-preview xr-preview'>(1980-07-02, 1980-08-01] ... (20...</div><input id='attrs-51b9c5bf-59b2-45f7-93a9-99744db558c2' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-51b9c5bf-59b2-45f7-93a9-99744db558c2' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c881e817-cda4-415c-b815-5ad445a749bc' class='xr-var-data-in' type='checkbox'><label for='data-c881e817-cda4-415c-b815-5ad445a749bc' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([Interval('1980-07-02', '1980-08-01', closed='right'),\n",
+ " dtype=int64)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>interval</span></div><div class='xr-var-dims'>(anchor_year)</div><div class='xr-var-dtype'>object</div><div class='xr-var-preview xr-preview'>(1980-07-02, 1980-08-01] ... (20...</div><input id='attrs-78c7815f-5b0b-43b4-a8ee-8ba7cbdf6d57' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-78c7815f-5b0b-43b4-a8ee-8ba7cbdf6d57' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-47d98346-f0f3-4b4d-be33-8d9c6f61b92a' class='xr-var-data-in' type='checkbox'><label for='data-47d98346-f0f3-4b4d-be33-8d9c6f61b92a' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([Interval('1980-07-02', '1980-08-01', closed='right'),\n",
" Interval('1981-07-02', '1981-08-01', closed='right'),\n",
" Interval('1982-07-02', '1982-08-01', closed='right'),\n",
" Interval('1983-07-02', '1983-08-01', closed='right'),\n",
@@ -569,21 +572,20 @@
" Interval('2015-07-02', '2015-08-01', closed='right'),\n",
" Interval('2016-07-02', '2016-08-01', closed='right'),\n",
" Interval('2017-07-02', '2017-08-01', closed='right'),\n",
- " Interval('2018-07-02', '2018-08-01', closed='right')], dtype=object)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>anchor_year</span></div><div class='xr-var-dims'>(anchor_year)</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>1980 1981 1982 ... 2016 2017 2018</div><input id='attrs-28bf1820-f31f-4cd8-8f28-1f70b627f934' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-28bf1820-f31f-4cd8-8f28-1f70b627f934' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-8b53caf6-01e7-48cb-9ba0-3c24fd03fadc' class='xr-var-data-in' type='checkbox'><label for='data-8b53caf6-01e7-48cb-9ba0-3c24fd03fadc' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991,\n",
- " 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,\n",
- " 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,\n",
- " 2016, 2017, 2018], dtype=int64)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>i_interval</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>int64</div><div class='xr-var-preview xr-preview'>1</div><input id='attrs-927c990d-58a9-42e9-88d9-05a8b451a0e1' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-927c990d-58a9-42e9-88d9-05a8b451a0e1' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-c9cbd978-62e5-4f6b-b471-e0b866de011f' class='xr-var-data-in' type='checkbox'><label for='data-c9cbd978-62e5-4f6b-b471-e0b866de011f' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array(1, dtype=int64)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>target</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>bool</div><div class='xr-var-preview xr-preview'>False</div><input id='attrs-13417705-633c-4a4d-bcca-7aef6bb48cb1' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-13417705-633c-4a4d-bcca-7aef6bb48cb1' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-57435aa5-d3cc-42a2-9fab-c3f1181d81f2' class='xr-var-data-in' type='checkbox'><label for='data-57435aa5-d3cc-42a2-9fab-c3f1181d81f2' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array(False)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>cluster_labels</span></div><div class='xr-var-dims'>(cluster_labels)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>-2.0 0.0 1.0</div><input id='attrs-c0794742-d215-4833-a607-f55b9d260507' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-c0794742-d215-4833-a607-f55b9d260507' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-085d4cba-0134-429a-8b20-2f8ee0da0b19' class='xr-var-data-in' type='checkbox'><label for='data-085d4cba-0134-429a-8b20-2f8ee0da0b19' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([-2., 0., 1.])</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-edc51e75-c5d1-4d3d-acb8-d29e400324e0' class='xr-section-summary-in' type='checkbox' disabled ><label for='section-edc51e75-c5d1-4d3d-acb8-d29e400324e0' class='xr-section-summary' title='Expand/collapse section'>Attributes: <span>(0)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><dl class='xr-attrs'></dl></div></li></ul></div></div>"
+ " Interval('2018-07-02', '2018-08-01', closed='right')], dtype=object)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>target</span></div><div class='xr-var-dims'>()</div><div class='xr-var-dtype'>bool</div><div class='xr-var-preview xr-preview'>False</div><input id='attrs-9c6a8913-5ff1-4399-9a14-1e92e0ecaf40' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-9c6a8913-5ff1-4399-9a14-1e92e0ecaf40' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-f7a6b906-d6f1-4a23-8849-70bd9c64b8bf' class='xr-var-data-in' type='checkbox'><label for='data-f7a6b906-d6f1-4a23-8849-70bd9c64b8bf' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array(False)</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span class='xr-has-index'>cluster_labels</span></div><div class='xr-var-dims'>(cluster_labels)</div><div class='xr-var-dtype'>int32</div><div class='xr-var-preview xr-preview'>-2 0 1</div><input id='attrs-3666865c-b0b6-4939-8d9f-46eeeef17953' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-3666865c-b0b6-4939-8d9f-46eeeef17953' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-a225f50b-a75d-48fd-972a-b3cdcbadc88a' class='xr-var-data-in' type='checkbox'><label for='data-a225f50b-a75d-48fd-972a-b3cdcbadc88a' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([-2, 0, 1])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>latitude</span></div><div class='xr-var-dims'>(cluster_labels)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>36.05 nan 29.44</div><input id='attrs-83eedce7-6a6b-447b-acf3-da3c8599601d' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-83eedce7-6a6b-447b-acf3-da3c8599601d' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-28d9eff3-8d17-477b-a4c4-3eb11c127cb7' class='xr-var-data-in' type='checkbox'><label for='data-28d9eff3-8d17-477b-a4c4-3eb11c127cb7' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([36.0508552, nan, 29.4398051])</pre></div></li><li class='xr-var-item'><div class='xr-var-name'><span>longitude</span></div><div class='xr-var-dims'>(cluster_labels)</div><div class='xr-var-dtype'>float64</div><div class='xr-var-preview xr-preview'>223.9 nan 185.4</div><input id='attrs-58fdb13b-0e3c-4e91-a117-8de91280dfb8' class='xr-var-attrs-in' type='checkbox' disabled><label for='attrs-58fdb13b-0e3c-4e91-a117-8de91280dfb8' title='Show/Hide attributes'><svg class='icon xr-icon-file-text2'><use xlink:href='#icon-file-text2'></use></svg></label><input id='data-9729360d-7b98-4363-a1b0-c41a3e1d5a28' class='xr-var-data-in' type='checkbox'><label for='data-9729360d-7b98-4363-a1b0-c41a3e1d5a28' title='Show/Hide data repr'><svg class='icon xr-icon-database'><use xlink:href='#icon-database'></use></svg></label><div class='xr-var-attrs'><dl class='xr-attrs'></dl></div><div class='xr-var-data'><pre>array([223.86658208, nan, 185.40970765])</pre></div></li></ul></div></li><li class='xr-section-item'><input id='section-b6f17ab0-1e40-4ee4-a636-991a140d2d05' class='xr-section-summary-in' type='checkbox' disabled ><label for='section-b6f17ab0-1e40-4ee4-a636-991a140d2d05' class='xr-section-summary' title='Expand/collapse section'>Attributes: <span>(0)</span></label><div class='xr-section-inline-details'></div><div class='xr-section-details'><dl class='xr-attrs'></dl></div></li></ul></div></div>"
],
"text/plain": [
"<xarray.DataArray 'sst' (cluster_labels: 3, anchor_year: 39)>\n",
"290.8 291.0 290.7 290.1 291.1 291.3 ... 299.0 299.5 298.9 298.9 299.2 298.2\n",
"Coordinates:\n",
+ " * anchor_year (anchor_year) int32 1980 1981 1982 1983 ... 2016 2017 2018\n",
+ " i_interval int64 1\n",
" index (anchor_year) int64 1 13 25 37 49 61 ... 409 421 433 445 457\n",
" interval (anchor_year) object (1980-07-02, 1980-08-01] ... (2018-0...\n",
- " * anchor_year (anchor_year) int64 1980 1981 1982 1983 ... 2016 2017 2018\n",
- " i_interval int64 1\n",
" target bool False\n",
- " * cluster_labels (cluster_labels) float64 -2.0 0.0 1.0"
+ " * cluster_labels (cluster_labels) int32 -2 0 1\n",
+ " latitude (cluster_labels) float64 36.05 nan 29.44\n",
+ " longitude (cluster_labels) float64 223.9 nan 185.4"
]
},
"execution_count": 5,
@@ -592,7 +594,8 @@
}
],
"source": [
- "clustered_data = rgdr.fit(precursor_field)\n",
+ "rgdr.fit(precursor_field, target_timeseries)\n",
+ "clustered_data = rgdr.transform(precursor_field)\n",
"xr.set_options(display_expand_data=False) # Hide the full data repr\n",
"clustered_data"
]
@@ -612,7 +615,7 @@
{
"data": {
"text/plain": [
- "<matplotlib.legend.Legend at 0x2df7dc7b0a0>"
+ "<matplotlib.legend.Legend at 0x1dc9fe35060>"
]
},
"execution_count": 6,
diff --git a/s2spy/rgdr/rgdr.py b/s2spy/rgdr/rgdr.py
index 35a415f..0e505ca 100644
--- a/s2spy/rgdr/rgdr.py
+++ b/s2spy/rgdr/rgdr.py
@@ -120,7 +120,7 @@ def masked_spherical_dbscan(
coords = np.radians(coords)
# Prepare labels, default value is 0 (not in cluster)
- labels = np.zeros(len(coords))
+ labels = np.zeros(len(coords), dtype=int)
for sign, sign_mask in zip([1, -1], [data["corr"] >= 0, data["corr"] < 0]):
mask = np.logical_and(data["p_val"] < dbscan_params["alpha"], sign_mask)
@@ -224,7 +224,7 @@ class RGDR:
"""Response Guided Dimensionality Reduction."""
def __init__(
- self, timeseries, eps_km=600, alpha=0.05, min_area_km2=3000**2
+ self, eps_km: float = 600, alpha: float = 0.05, min_area_km2: float = 3000**2
) -> None:
"""Response Guided Dimensionality Reduction (RGDR).
@@ -240,14 +240,52 @@ class RGDR:
min_area_km2 (float): The minimum area of a cluster. Clusters smaller than
this minimum area will be discarded.
"""
- self.timeseries = timeseries
self._clusters = None
self._area = None
self._dbscan_params = {"eps": eps_km, "alpha": alpha, "min_area": min_area_km2}
+ def get_correlation(
+ self,
+ precursor: xr.DataArray,
+ timeseries: xr.DataArray,
+ ) -> Tuple[xr.DataArray, xr.DataArray]:
+ """Calculates the correlation and p-value between input precursor and timeseries.
+
+ Args:
+ precursor: Precursor field data with the dimensions
+ 'latitude', 'longitude', and 'anchor_year'
+ timeseries: Timeseries data with only the dimension 'anchor_year'
+
+ Returns:
+ (correlation, p_value): DataArrays containing the correlation and p-value.
+ """
+ if not isinstance(precursor, xr.DataArray):
+ raise ValueError("Please provide an xr.DataArray, not a dataset")
+
+ return correlation(precursor, timeseries, corr_dim="anchor_year")
+
+ def get_clusters(
+ self,
+ precursor: xr.DataArray,
+ timeseries: xr.DataArray,
+ ) -> xr.DataArray:
+ """Generates clusters for the precursor data.
+
+ Args:
+ precursor: Precursor field data with the dimensions
+ 'latitude', 'longitude', and 'anchor_year'
+ timeseries: Timeseries data with only the dimension 'anchor_year'
+
+ Returns:
+ DataArray containing the clusters as masks.
+ """
+ corr, p_val = self.get_correlation(precursor, timeseries)
+ return masked_spherical_dbscan(precursor, corr, p_val, self._dbscan_params)
+
def plot_correlation(
self,
precursor: xr.DataArray,
+ timeseries: xr.DataArray,
ax1: Optional[plt.Axes] = None,
ax2: Optional[plt.Axes] = None,
) -> List[Type[mpl.collections.QuadMesh]]:
@@ -255,22 +293,19 @@ class RGDR:
initiated RGDR class and input precursor field.
Args:
- precursor (xr.DataArray): Precursor field data with the dimensions
+ precursor: Precursor field data with the dimensions
'latitude', 'longitude', and 'anchor_year'
- ax1 (plt.Axes, optional): a matplotlib axis handle to plot
+ timeseries: Timeseries data with only the dimension 'anchor_year'
+ ax1: a matplotlib axis handle to plot
the correlation values into. If None, an axis handle will be created
instead.
- ax2 (plt.Axes, optional): a matplotlib axis handle to plot
+ ax2: a matplotlib axis handle to plot
the p-values into. If None, an axis handle will be created instead.
Returns:
List[mpl.collections.QuadMesh]: List of matplotlib artists.
"""
-
- if not isinstance(precursor, xr.DataArray):
- raise ValueError("Please provide an xr.DataArray, not a dataset")
-
- corr, p_val = correlation(precursor, self.timeseries, corr_dim="anchor_year")
+ corr, p_val = self.get_correlation(precursor, timeseries)
if (ax1 is None) and (ax2 is None):
_, (ax1, ax2) = plt.subplots(ncols=2)
@@ -288,30 +323,32 @@ class RGDR:
return [plot1, plot2]
def plot_clusters(
- self, precursor: xr.DataArray, ax: Optional[plt.Axes] = None
+ self,
+ precursor: xr.DataArray,
+ timeseries: xr.DataArray,
+ ax: Optional[plt.Axes] = None,
) -> Type[mpl.collections.QuadMesh]:
"""Generates a figure showing the clusters resulting from the initiated RGDR
class and input precursor field.
Args:
- precursor: Precursor field data with the dimensions 'latitude', 'longitude',
- and 'anchor_year'
+ precursor: Precursor field data with the dimensions
+ 'latitude', 'longitude', and 'anchor_year'
+ timeseries: Timeseries data with only the dimension 'anchor_year'
ax (plt.Axes, optional): a matplotlib axis handle to plot the clusters
into. If None, an axis handle will be created instead.
Returns:
matplotlib.collections.QuadMesh: Matplotlib artist.
"""
- corr, p_val = correlation(precursor, self.timeseries, corr_dim="anchor_year")
-
- clusters = masked_spherical_dbscan(precursor, corr, p_val, self._dbscan_params)
+ clusters = self.get_clusters(precursor, timeseries)
if ax is None:
_, ax = plt.subplots()
return clusters.cluster_labels.plot(cmap="viridis", ax=ax)
- def fit(self, precursor: xr.DataArray) -> xr.DataArray:
+ def fit(self, precursor: xr.DataArray, timeseries: xr.DataArray):
"""Fits RGDR clusters to precursor data.
Performs DBSCAN clustering on a prepared DataArray, and then groups the data by
@@ -330,13 +367,15 @@ class RGDR:
Args:
precursor: Precursor field data with the dimensions 'latitude', 'longitude',
and 'anchor_year'
+ timeseries: Timeseries data with only the dimension 'anchor_year', which
+ will be correlated with the precursor field.
Returns:
xr.DataArray: The precursor data, with the latitute and longitude dimensions
reduced to clusters.
"""
- corr, p_val = correlation(precursor, self.timeseries, corr_dim="anchor_year")
+ corr, p_val = correlation(precursor, timeseries, corr_dim="anchor_year")
masked_data = masked_spherical_dbscan(
precursor, corr, p_val, self._dbscan_params
@@ -345,12 +384,7 @@ class RGDR:
self._clusters = masked_data.cluster_labels
self._area = masked_data.area
- reduced_precursor = utils.weighted_groupby(
- masked_data, groupby="cluster_labels", weight="area"
- )
-
- # Add the geographical centers for later alignment between, e.g., splits
- return utils.geographical_cluster_center(masked_data, reduced_precursor)
+ return self
def transform(self, data: xr.DataArray) -> xr.DataArray:
"""Apply RGDR on the input data, based on the previous fit.
@@ -366,8 +400,26 @@ class RGDR:
data["cluster_labels"] = self._clusters
data["area"] = self._area
+ # Add the geographical centers for later alignment between, e.g., splits
reduced_data = utils.weighted_groupby(
data, groupby="cluster_labels", weight="area"
)
return utils.geographical_cluster_center(data, reduced_data)
+
+ def fit_transform(self, precursor: xr.DataArray, timeseries: xr.DataArray):
+ """Fits RGDR clusters to precursor data, and applies RGDR on the input data.
+
+ Args:
+ precursor: Precursor field data with the dimensions 'latitude', 'longitude',
+ and 'anchor_year'
+ timeseries: Timeseries data with only the dimension 'anchor_year', which
+ will be correlated with the precursor field.
+
+ Returns:
+ xr.DataArray: The precursor data, with the latitute and longitude dimensions
+ reduced to clusters.
+ """
+
+ self.fit(precursor, timeseries)
+ return self.transform(precursor)
|
ARM-software__mango-42
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"mango/domain/domain_space.py:domain_space.create_mappings"
],
"edited_modules": [
"mango/domain/domain_space.py:domain_space"
]
},
"file": "mango/domain/domain_space.py"
}
] |
ARM-software/mango
|
f1b2aaef4b2d6ba5b5ed1667346c1d9cfb708d85
|
Variable type issue in domain_space.py file
System: Ubuntu 18.04, Python; 3.8.8 (via conda environment), Tensorflow: 2.4.0 (with GPU), numpy: 1.18.5
Error happens when using TF in conjunction with Mango for neural architecture search.
In https://github.com/ARM-software/mango/blob/master/mango/domain/domain_space.py, line 120:
```
...
# we need to see the index where: domain[x] appears in mapping[x]
index = mapping_categorical[x].index(domain[x])
...
```
The variable mapping_categorical[x] automatically changes to numpy array for some iterations and remains as a list for some iterations. This causes an error: "numpy.ndarray() has no attribute index". I am not sure why the variable would return list for some iterations and a numpy array for other iterations. I made a workaround replacing the lines as follows:
```
...
# we need to see the index where: domain[x] appears in mapping[x]
if(type(mapping_categorical[x]).__name__ == 'list'):
index = mapping_categorical[x].index(domain[x])
else:
index = mapping_categorical[x].tolist().index(domain[x])
...
```
|
diff --git a/mango/domain/domain_space.py b/mango/domain/domain_space.py
index 86cf9da..b02f833 100644
--- a/mango/domain/domain_space.py
+++ b/mango/domain/domain_space.py
@@ -70,7 +70,7 @@ class domain_space():
pass # we are not doing anything at present, and will directly use its value for GP.
elif isinstance(param_dict[par], range):
- mapping_int[par] = param_dict[par]
+ mapping_int[par] = list(param_dict[par])
elif isinstance(param_dict[par], Iterable):
@@ -83,11 +83,11 @@ class domain_space():
all_int = False
if all_int:
- mapping_int[par] = param_dict[par]
+ mapping_int[par] = list(param_dict[par])
# For lists with mixed type, floats or strings we consider them categorical or discrete
else:
- mapping_categorical[par] = param_dict[par]
+ mapping_categorical[par] = list(param_dict[par])
self.mapping_categorical = mapping_categorical
self.mapping_int = mapping_int
|
ARMmbed__greentea-237
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"mbed_greentea/mbed_report_api.py:exporter_json",
"mbed_greentea/mbed_report_api.py:exporter_testcase_junit",
"mbed_greentea/mbed_report_api.py:get_result_overlay_dropdowns",
"mbed_greentea/mbed_report_api.py:exporter_html"
],
"edited_modules": [
"mbed_greentea/mbed_report_api.py:exporter_json",
"mbed_greentea/mbed_report_api.py:exporter_testcase_junit",
"mbed_greentea/mbed_report_api.py:get_result_overlay_dropdowns",
"mbed_greentea/mbed_report_api.py:exporter_html"
]
},
"file": "mbed_greentea/mbed_report_api.py"
}
] |
ARMmbed/greentea
|
86f5ec3211a8f7f324bcdd3201012945ee0534ac
|
mbedgt crash with float division by zero
Hi
Here is my command:
mbedgt -V -v -t NUCLEO_F401RE-ARM,NUCLEO_F401RE-GCC_ARM,NUCLEO_F401RE-IAR,NUCLEO_F410RB-ARM,NUCLEO_F410RB-GCC_ARM,NUCLEO_F410RB-IAR,NUCLEO_F411RE-ARM,NUCLEO_F411RE-GCC_ARM,NUCLEO_F411RE-IAR --report-html=/c/xxx.html
It has crashed:
...
mbedgt: all tests finished!
mbedgt: shuffle seed: 0.3680156551
mbedgt: exporting to HTML file
mbedgt: unexpected error:
float division by zero
Traceback (most recent call last):
File "C:\Python27\Scripts\mbedgt-script.py", line 11, in <module>
load_entry_point('mbed-greentea==1.2.6', 'console_scripts', 'mbedgt')()
File "c:\python27\lib\site-packages\mbed_greentea\mbed_greentea_cli.py", line 401, in main
cli_ret = main_cli(opts, args)
File "c:\python27\lib\site-packages\mbed_greentea\mbed_greentea_cli.py", line 1050, in main_cli
html_report = exporter_html(test_report)
File "c:\python27\lib\site-packages\mbed_greentea\mbed_report_api.py", line 747, in exporter_html
int((test_results['single_test_passes']*100.0)/test_results['single_test_count']),
ZeroDivisionError: float division by zero
|
diff --git a/mbed_greentea/mbed_report_api.py b/mbed_greentea/mbed_report_api.py
index da3f0d9..82acb5c 100644
--- a/mbed_greentea/mbed_report_api.py
+++ b/mbed_greentea/mbed_report_api.py
@@ -38,6 +38,13 @@ def exporter_json(test_result_ext, test_suite_properties=None):
@details This is a machine friendly format
"""
import json
+ for target in test_result_ext.values():
+ for suite in target.values():
+ try:
+ suite["single_test_output"] = suite["single_test_output"]\
+ .decode("unicode_escape")
+ except KeyError:
+ pass
return json.dumps(test_result_ext, indent=4)
@@ -211,7 +218,10 @@ def exporter_testcase_junit(test_result_ext, test_suite_properties=None):
test_cases.append(tc)
ts_name = target_name
- test_build_properties = test_suite_properties[target_name] if target_name in test_suite_properties else None
+ if test_suite_properties and target_name in test_suite_properties:
+ test_build_properties = test_suite_properties[target_name]
+ else:
+ test_build_properties = None
ts = TestSuite(ts_name, test_cases, properties=test_build_properties)
test_suites.append(ts)
@@ -584,7 +594,9 @@ def get_result_overlay_dropdowns(result_div_id, test_results):
result_output_div_id = "%s_output" % result_div_id
result_output_dropdown = get_dropdown_html(result_output_div_id,
"Test Output",
- test_results['single_test_output'].rstrip("\n"),
+ test_results['single_test_output']
+ .decode("unicode-escape")
+ .rstrip("\n"),
output_text=True)
# Add a dropdown for the testcases if they are present
@@ -740,10 +752,14 @@ def exporter_html(test_result_ext, test_suite_properties=None):
test_results['single_test_count'] += 1
result_class = get_result_colour_class(test_results['single_test_result'])
+ try:
+ percent_pass = int((test_results['single_test_passes']*100.0)/test_results['single_test_count'])
+ except ZeroDivisionError:
+ percent_pass = 100
this_row += result_cell_template % (result_class,
result_div_id,
test_results['single_test_result'],
- int((test_results['single_test_passes']*100.0)/test_results['single_test_count']),
+ percent_pass,
test_results['single_test_passes'],
test_results['single_test_count'],
result_overlay)
|
ARMmbed__greentea-243
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"mbed_greentea/mbed_report_api.py:exporter_json",
"mbed_greentea/mbed_report_api.py:get_result_overlay_dropdowns"
],
"edited_modules": [
"mbed_greentea/mbed_report_api.py:exporter_json",
"mbed_greentea/mbed_report_api.py:get_result_overlay_dropdowns"
]
},
"file": "mbed_greentea/mbed_report_api.py"
}
] |
ARMmbed/greentea
|
8f7b28f8ec739156d238304fa4f5f2e5156536f5
|
mbedgt crash with UnicodeDecodeError
Hi
I am sorry, but I still get some crash with the new green tea version ...
mbedgt: exporting to HTML file 'C:/mcu/reports/report__mbed_os5_release_non_regression_F756ZG_mbed-os-5.5.7__2017_09_28_00_06.html'...
mbedgt: unexpected error:
'unicodeescape' codec can't decode bytes in position 6308-6310: truncated \uXXXX escape
Traceback (most recent call last):
File "C:\Python27\Scripts\mbedgt-script.py", line 11, in <module>
load_entry_point('mbed-greentea==1.3.0', 'console_scripts', 'mbedgt')()
File "c:\python27\lib\site-packages\mbed_greentea\mbed_greentea_cli.py", line 416, in main
cli_ret = main_cli(opts, args)
File "c:\python27\lib\site-packages\mbed_greentea\mbed_greentea_cli.py", line 1067, in main_cli
html_report = exporter_html(test_report)
File "c:\python27\lib\site-packages\mbed_greentea\mbed_report_api.py", line 747, in exporter_html
test_results)
File "c:\python27\lib\site-packages\mbed_greentea\mbed_report_api.py", line 636, in get_result_overlay
overlay_dropdowns = get_result_overlay_dropdowns(result_div_id, test_results)
File "c:\python27\lib\site-packages\mbed_greentea\mbed_report_api.py", line 598, in get_result_overlay_dropdowns
.decode("unicode-escape")
UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 6308-6310: truncated \uXXXX escape
@theotherjimmy
|
diff --git a/mbed_greentea/mbed_report_api.py b/mbed_greentea/mbed_report_api.py
index 166bc29..22a3778 100644
--- a/mbed_greentea/mbed_report_api.py
+++ b/mbed_greentea/mbed_report_api.py
@@ -42,7 +42,7 @@ def exporter_json(test_result_ext, test_suite_properties=None):
for suite in target.values():
try:
suite["single_test_output"] = suite["single_test_output"]\
- .decode("unicode_escape")
+ .decode("utf-8", "replace")
except KeyError:
pass
return json.dumps(test_result_ext, indent=4)
@@ -603,7 +603,7 @@ def get_result_overlay_dropdowns(result_div_id, test_results):
result_output_dropdown = get_dropdown_html(result_output_div_id,
"Test Output",
test_results['single_test_output']
- .decode("unicode-escape")
+ .decode("utf-8", "replace")
.rstrip("\n"),
output_text=True)
|
ARMmbed__greentea-250
|
[
{
"changes": {
"added_entities": [
"mbed_greentea/mbed_target_info.py:suppress",
"mbed_greentea/mbed_target_info.py:_get_platform_property_from_default",
"mbed_greentea/mbed_target_info.py:_get_platform_property_from_info_mapping",
"mbed_greentea/mbed_target_info.py:_platform_property_from_targets_json",
"mbed_greentea/mbed_target_info.py:_find_targets_json",
"mbed_greentea/mbed_target_info.py:_get_platform_property_from_targets"
],
"added_modules": [
"mbed_greentea/mbed_target_info.py:suppress",
"mbed_greentea/mbed_target_info.py:_get_platform_property_from_default",
"mbed_greentea/mbed_target_info.py:_get_platform_property_from_info_mapping",
"mbed_greentea/mbed_target_info.py:_platform_property_from_targets_json",
"mbed_greentea/mbed_target_info.py:_find_targets_json",
"mbed_greentea/mbed_target_info.py:_get_platform_property_from_targets"
],
"edited_entities": [
"mbed_greentea/mbed_target_info.py:get_platform_property",
"mbed_greentea/mbed_target_info.py:get_platform_property_from_targets"
],
"edited_modules": [
"mbed_greentea/mbed_target_info.py:get_platform_property",
"mbed_greentea/mbed_target_info.py:get_platform_property_from_targets"
]
},
"file": "mbed_greentea/mbed_target_info.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "setup.py"
}
] |
ARMmbed/greentea
|
b8bcffbb7aaced094f252a4ddfe930e8237fb484
|
Target property priority incorrect
Currently we have priority as follows:
```
internal yotta blob > targets.json > tool default
```
This is a bug.
Instead the priority should be:
```
targets.json /w default > internal yotta blob > tool delaut
```
This implies a few test cases:
In targets.json | In yotta blob | property used | Currently Works
---------------------- | ------------- | ---------------- | ---------------
Yes, with property | No | `targets.json` | Yes
Yes, without property| No | default | Yes
Yes, with property | Yes | `targets.json` | No
Yes, without property | Yes | default | No
No | No | default | Yes
No | Yes | yotta blob | Yes
@bridadan Is this the issue masked by #248?
|
diff --git a/mbed_greentea/mbed_target_info.py b/mbed_greentea/mbed_target_info.py
index 356676b..c825bcf 100644
--- a/mbed_greentea/mbed_target_info.py
+++ b/mbed_greentea/mbed_target_info.py
@@ -20,6 +20,17 @@ Author: Przemyslaw Wirkus <Przemyslaw.Wirkus@arm.com>
import os
import re
import json
+from os import walk
+try:
+ from contextlib import suppress
+except ImportError:
+ from contextlib import contextmanager
+ @contextmanager
+ def suppress(*excs):
+ try:
+ yield
+ except excs:
+ pass
from mbed_greentea.mbed_common_api import run_cli_process
from mbed_greentea.mbed_greentea_log import gt_logger
@@ -381,82 +392,65 @@ def get_platform_property(platform, property):
:return: property value, None if property not found
"""
- # First load from targets.json if available
- value_from_targets_json = get_platform_property_from_targets(platform, property)
- if value_from_targets_json:
- return value_from_targets_json
-
- # Check if info is available for a specific platform
- if platform in TARGET_INFO_MAPPING:
- if property in TARGET_INFO_MAPPING[platform]['properties']:
- return TARGET_INFO_MAPPING[platform]['properties'][property]
+ default = _get_platform_property_from_default(property)
+ from_targets_json = _get_platform_property_from_targets(
+ platform, property, default)
+ if from_targets_json:
+ return from_targets_json
+ from_info_mapping = _get_platform_property_from_info_mapping(platform, property)
+ if from_info_mapping:
+ return from_info_mapping
+ return default
+
+def _get_platform_property_from_default(property):
+ with suppress(KeyError):
+ return TARGET_INFO_MAPPING['default'][property]
+
+def _get_platform_property_from_info_mapping(platform, property):
+ with suppress(KeyError):
+ return TARGET_INFO_MAPPING[platform]['properties'][property]
+
+def _platform_property_from_targets_json(targets, platform, property, default):
+ """! Get a platforms's property from the target data structure in
+ targets.json. Takes into account target inheritance.
+ @param targets Data structure parsed from targets.json
+ @param platform Name of the platform
+ @param property Name of the property
+ @param default the fallback value if none is found, but the target exists
+ @return property value, None if property not found
- # Check if default data is available
- if 'default' in TARGET_INFO_MAPPING:
- if property in TARGET_INFO_MAPPING['default']:
- return TARGET_INFO_MAPPING['default'][property]
-
- return None
+ """
+ with suppress(KeyError):
+ return targets[platform][property]
+ with suppress(KeyError):
+ for inherited_target in targets[platform]['inherits']:
+ result = _platform_property_from_targets_json(targets, inherited_target, property, None)
+ if result:
+ return result
+ if platform in targets:
+ return default
+
+IGNORED_DIRS = ['.build', 'BUILD', 'tools']
+
+def _find_targets_json(path):
+ for root, dirs, files in walk(path, followlinks=True):
+ for ignored_dir in IGNORED_DIRS:
+ if ignored_dir in dirs:
+ dirs.remove(ignored_dir)
+ if 'targets.json' in files:
+ yield os.path.join(root, 'targets.json')
-def get_platform_property_from_targets(platform, property):
+def _get_platform_property_from_targets(platform, property, default):
"""
Load properties from targets.json file somewhere in the project structure
:param platform:
:return: property value, None if property not found
"""
-
- def get_platform_property_from_targets(targets, platform, property):
- """! Get a platforms's property from the target data structure in
- targets.json. Takes into account target inheritance.
- @param targets Data structure parsed from targets.json
- @param platform Name of the platform
- @param property Name of the property
- @return property value, None if property not found
-
- """
-
- result = None
- if platform in targets:
- if property in targets[platform]:
- result = targets[platform][property]
- elif 'inherits' in targets[platform]:
- result = None
- for inherited_target in targets[platform]['inherits']:
- result = get_platform_property_from_targets(targets, inherited_target, property)
-
- # Stop searching after finding the first value for the property
- if result:
- break
-
- return result
-
- result = None
- targets_json_path = []
- for root, dirs, files in os.walk(os.getcwd(), followlinks=True):
- ignored_dirs = ['.build', 'BUILD', 'tools']
-
- for ignored_dir in ignored_dirs:
- if ignored_dir in dirs:
- dirs.remove(ignored_dir)
-
- if 'targets.json' in files:
- targets_json_path.append(os.path.join(root, 'targets.json'))
-
- if not targets_json_path:
- gt_logger.gt_log_warn("No targets.json files found, using default target properties")
-
- for targets_path in targets_json_path:
- try:
+ for targets_path in _find_targets_json(os.getcwd()):
+ with suppress(IOError, ValueError):
with open(targets_path, 'r') as f:
targets = json.load(f)
-
- # Load property from targets.json
- result = get_platform_property_from_targets(targets, platform, property)
-
- # If a valid property was found, stop looking
+ result = _platform_property_from_targets_json(targets, platform, property, default)
if result:
- break
- except Exception:
- continue
- return result
+ return result
diff --git a/setup.py b/setup.py
index e98e109..0734dfe 100644
--- a/setup.py
+++ b/setup.py
@@ -50,13 +50,15 @@ setup(name='mbed-greentea',
license=LICENSE,
test_suite = 'test',
entry_points={
- "console_scripts": ["mbedgt=mbed_greentea.mbed_greentea_cli:main",],
+ "console_scripts": ["mbedgt=mbed_greentea.mbed_greentea_cli:main",],
},
install_requires=["PrettyTable>=0.7.2",
- "PySerial>=3.0",
- "mbed-host-tests>=1.2.0",
- "mbed-ls>=1.2.15",
- "junit-xml",
- "lockfile",
- "mock",
- "colorama>=0.3,<0.4"])
+ "PySerial>=3.0",
+ "mbed-host-tests>=1.2.0",
+ "mbed-ls>=1.2.15",
+ "junit-xml",
+ "lockfile",
+ "mock",
+ "six",
+ "colorama>=0.3,<0.4"])
+
|
ARMmbed__greentea-263
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"mbed_greentea/mbed_greentea_cli.py:create_filtered_test_list"
],
"edited_modules": [
"mbed_greentea/mbed_greentea_cli.py:create_filtered_test_list"
]
},
"file": "mbed_greentea/mbed_greentea_cli.py"
}
] |
ARMmbed/greentea
|
68508c5f4d7cf0635c75399d0ff7cfa896fdf2cc
|
Test names are not correctly globbed
Test names only respect a wildcard that is placed at the end of the string. Ex. "mbed-os-*".
However, it does not respect the wildcard anywhere else. Ex. "*-timer"
The build tools accept these wildcards, so greentea should as well. This is the line responsible: https://github.com/ARMmbed/greentea/blob/32b95b44be653c3db527c02e1c5e1ffdc7d37f6f/mbed_greentea/mbed_greentea_cli.py#L146
Should be switched to `fnmatch`.
(This is mostly a note to myself to fix it)
|
diff --git a/mbed_greentea/mbed_greentea_cli.py b/mbed_greentea/mbed_greentea_cli.py
index f6a13c4..446b965 100644
--- a/mbed_greentea/mbed_greentea_cli.py
+++ b/mbed_greentea/mbed_greentea_cli.py
@@ -23,6 +23,7 @@ import os
import sys
import random
import optparse
+import fnmatch
from time import time
try:
from Queue import Queue
@@ -119,18 +120,6 @@ def create_filtered_test_list(ctest_test_list, test_by_names, skip_test, test_sp
@return
"""
- def filter_names_by_prefix(test_case_name_list, prefix_name):
- """!
- @param test_case_name_list List of all test cases
- @param prefix_name Prefix of test name we are looking for
- @result Set with names of test names starting with 'prefix_name'
- """
- result = list()
- for test_name in test_case_name_list:
- if test_name.startswith(prefix_name):
- result.append(test_name)
- return sorted(result)
-
filtered_ctest_test_list = ctest_test_list
test_list = None
invalid_test_names = []
@@ -143,17 +132,15 @@ def create_filtered_test_list(ctest_test_list, test_by_names, skip_test, test_sp
gt_logger.gt_log("test case filter (specified with -n option)")
for test_name in set(test_list):
- if test_name.endswith('*'):
- # This 'star-sufix' filter allows users to filter tests with fixed prefixes
- # Example: -n 'TESTS-mbed_drivers* will filter all test cases with name starting with 'TESTS-mbed_drivers'
- for test_name_filtered in filter_names_by_prefix(ctest_test_list.keys(), test_name[:-1]):
- gt_logger.gt_log_tab("test filtered in '%s'"% gt_logger.gt_bright(test_name_filtered))
- filtered_ctest_test_list[test_name_filtered] = ctest_test_list[test_name_filtered]
- elif test_name not in ctest_test_list:
- invalid_test_names.append(test_name)
+ gt_logger.gt_log_tab(test_name)
+ matches = [test for test in ctest_test_list.keys() if fnmatch.fnmatch(test, test_name)]
+ gt_logger.gt_log_tab(str(ctest_test_list))
+ if matches:
+ for match in matches:
+ gt_logger.gt_log_tab("test filtered in '%s'"% gt_logger.gt_bright(match))
+ filtered_ctest_test_list[match] = ctest_test_list[match]
else:
- gt_logger.gt_log_tab("test filtered in '%s'"% gt_logger.gt_bright(test_name))
- filtered_ctest_test_list[test_name] = ctest_test_list[test_name]
+ invalid_test_names.append(test_name)
if skip_test:
test_list = skip_test.split(',')
|
ARMmbed__yotta-802
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"yotta/install.py:installComponentAsDependency"
],
"edited_modules": [
"yotta/install.py:installComponentAsDependency"
]
},
"file": "yotta/install.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"yotta/lib/access.py:latestSuitableVersion"
],
"edited_modules": [
"yotta/lib/access.py:latestSuitableVersion"
]
},
"file": "yotta/lib/access.py"
},
{
"changes": {
"added_entities": [
"yotta/lib/git_access.py:GitWorkingCopy.commitVersion"
],
"added_modules": null,
"edited_entities": [
"yotta/lib/git_access.py:GitWorkingCopy.tipVersion"
],
"edited_modules": [
"yotta/lib/git_access.py:GitWorkingCopy"
]
},
"file": "yotta/lib/git_access.py"
},
{
"changes": {
"added_entities": [
"yotta/lib/github_access.py:_getCommitArchiveURL",
"yotta/lib/github_access.py:GithubComponent.commitVersion"
],
"added_modules": [
"yotta/lib/github_access.py:_getCommitArchiveURL"
],
"edited_entities": null,
"edited_modules": [
"yotta/lib/github_access.py:GithubComponent"
]
},
"file": "yotta/lib/github_access.py"
},
{
"changes": {
"added_entities": [
"yotta/lib/sourceparse.py:_getNonRegistryRef"
],
"added_modules": [
"yotta/lib/sourceparse.py:_getNonRegistryRef"
],
"edited_entities": [
"yotta/lib/sourceparse.py:_splitFragment",
"yotta/lib/sourceparse.py:_getGithubRef",
"yotta/lib/sourceparse.py:parseSourceURL",
"yotta/lib/sourceparse.py:parseTargetNameAndSpec",
"yotta/lib/sourceparse.py:parseModuleNameAndSpec"
],
"edited_modules": [
"yotta/lib/sourceparse.py:_splitFragment",
"yotta/lib/sourceparse.py:_getGithubRef",
"yotta/lib/sourceparse.py:parseSourceURL",
"yotta/lib/sourceparse.py:parseTargetNameAndSpec",
"yotta/lib/sourceparse.py:parseModuleNameAndSpec"
]
},
"file": "yotta/lib/sourceparse.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "yotta/link.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "yotta/link_target.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"yotta/main.py:main"
],
"edited_modules": [
"yotta/main.py:main"
]
},
"file": "yotta/main.py"
}
] |
ARMmbed/yotta
|
ae1cda2082f6f82c1c9f80f6194fcae62d228bc1
|
Install yotta modules from github with git credentials
I'd like to do following but it fails:
```
$ yotta install git@github.com:ARMmbed/module-x.git
info: get versions for git
Fatal Exception, yotta=0.17.2
Traceback (most recent call last):
File "/home/jaakor01/workspace/yotta_issue/venv/bin/yotta", line 4, in <module>
yotta.main()
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/main.py", line 61, in wrapped
return fn(*args, **kwargs)
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/main.py", line 46, in wrapped
return fn(*args, **kwargs)
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/main.py", line 243, in main
status = args.command(args, following_args)
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/install.py", line 62, in execCommand
return installComponent(args)
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/install.py", line 202, in installComponent
working_directory = path
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/lib/access.py", line 385, in satisfyVersion
name, version_required, working_directory, type=type, inherit_shrinkwrap = inherit_shrinkwrap
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/lib/access.py", line 314, in satisfyVersionByInstalling
v = latestSuitableVersion(name, version_required, _registryNamespaceForType(type))
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/lib/access.py", line 159, in latestSuitableVersion
local_clone = remote_component.clone()
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/lib/git_access.py", line 114, in clone
clone = vcs.Git.cloneToTemporaryDir(self.url)
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/lib/vcs.py", line 62, in cloneToTemporaryDir
return cls.cloneToDirectory(remote, tempfile.mkdtemp())
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/lib/vcs.py", line 69, in cloneToDirectory
cls._execCommands(commands)
File "/home/jaakor01/workspace/yotta_issue/venv/local/lib/python2.7/site-packages/yotta/lib/vcs.py", line 146, in _execCommands
raise VCSError("command failed: %s" % (err or out), returncode=returncode, command=cmd)
yotta.lib.vcs.VCSError: command failed: Cloning into '/tmp/tmpi_bJ_8'...
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
```
However, if I add the same address manually to `module.json` it works with `yotta update`.
```
"dependencies": {
"module-x":"git@github.com:ARMmbed/module-x.git#master"
},
```
|
diff --git a/docs/reference/buildsystem.md b/docs/reference/buildsystem.md
index e728c9f..6cc8bd9 100644
--- a/docs/reference/buildsystem.md
+++ b/docs/reference/buildsystem.md
@@ -30,7 +30,7 @@ The name of the library being built by the current module is available as
No header needs to be included for this definition to be available.
Use the [preprocessor stringification
-trick](https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html) to get the
+trick](https://gcc.gnu.org/onlinedocs/cpp/Stringification.html) to get the
module name as a string, if desired. Note that this definition is **not**
currently available when compiling tests, and there are other circumstances
where using custom CMake can make it unavailable.
diff --git a/docs/reference/commands.md b/docs/reference/commands.md
index 7269eca..30ee1bf 100755
--- a/docs/reference/commands.md
+++ b/docs/reference/commands.md
@@ -534,7 +534,7 @@ example:
## <a href="#yotta-uninstall" name="yotta-uninstall">#</a> yotta uninstall
-Synonyms: `yotta unlink`, `yotta rm`
+Synonyms: `yotta unlink`, `yotta rm`, `yotta un`
#### Synopsis
```
diff --git a/docs/reference/config.md b/docs/reference/config.md
index d56a2f5..43be6bb 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -267,7 +267,7 @@ definitions will be produced:
Note that string values are not quoted. If you want a quoted string,
either embed escaped quotes (`\"`) in the string value, or use the preprocessor
[stringification
-trick](https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html).
+trick](https://gcc.gnu.org/onlinedocs/cpp/Stringification.html).
JSON boolean values are converted to 1 or 0, and `null` values are converted to `NULL`.
diff --git a/docs/reference/module.md b/docs/reference/module.md
index 4bc38c5..57498c1 100755
--- a/docs/reference/module.md
+++ b/docs/reference/module.md
@@ -198,6 +198,10 @@ To specify a dependency on a github module, use one of the following forms:
Uses the latest committed version on the specified branch.
+ * `"usefulmodule": "username/repositoryname#commit-id"`
+
+ Uses the specified commit ID.
+
#### Depending on git Modules
To specify a module available from a non-Github git server as a dependency, use
a git URL:
@@ -206,8 +210,9 @@ a git URL:
* `"usefulmodule": "git+ssh://somwhere.com/anything/anywhere#<version specification>"`
* `"usefulmodule": "git+ssh://somwhere.com/anything/anywhere#<branch name>"`
* `"usefulmodule": "git+ssh://somwhere.com/anything/anywhere#<tag name>"`
+ * `"usefulmodule": "git+ssh://somwhere.com/anything/anywhere#<commit id>"`
* `"usefulmodule": "<anything>://somwhere.git"`
- * `"usefulmodule": "<anything>://somwhere.git#<version spec, tag, or branch name>"`
+ * `"usefulmodule": "<anything>://somwhere.git#<version spec, tag, branch name or commit id>"`
#### Depending on hg Modules
To specify a module available from a mercurial server as a dependency, use
diff --git a/docs/tutorial/privaterepos.md b/docs/tutorial/privaterepos.md
index 471d2de..630ad9a 100644
--- a/docs/tutorial/privaterepos.md
+++ b/docs/tutorial/privaterepos.md
@@ -24,18 +24,33 @@ Sometimes it may not be appropriate publish a module to the public package regis
The shorthand GitHub URL is formed of two parts: `<username>/<reponame>` where `<username>` is the GitHub user or organisation name of the repository owner and `<reponame>` is the name of the repositiry. e.g. the `yotta` repositry can be found at `ARMmbed/yotta`.
-You can specify a particular branch or tag to use by providing it in the URL. The supported GitHub URL formats are:
+You can specify a particular branch, tag or commit to use by providing it in the URL. The supported GitHub URL formats are:
```
username/reponame
username/reponame#<versionspec>
username/reponame#<branchname>
username/reponame#<tagname>
+username/reponame#<commit>
+https://github.com/username/reponame
+https://github.com/username/reponame#<branchname>
+https://github.com/username/reponame#<tagname>
+https://github.com/username/reponame#<commit>
```
+If the GitHub repository is public, the dependency will simply be downloaded. If the GitHub repository is private and this is the first time you are downloading from a private GitHub repository, you will be prompted to log in to GitHub using a URL.
+
+If you have a private GitHub repository and you would prefer to download it using SSH keys, you can use the following dependency form:
+
+```
+git@github.com:username/reponame.git
+git@github.com:username/reponame.git#<branchname>
+git@github.com:username/reponame.git#<tagname>
+git@github.com:username/reponame.git#<commit>
+```
###Other ways to depend on private repositories
-Using shorthand GitHub URLs is the easiest and reccomneded method of working with private repositories, however as not all projects are hosted on GitHub, `yotta` supports using git and hg URLs directly as well.
+Using shorthand GitHub URLs is the easiest and recommended method of working with private repositories, however as not all projects are hosted on GitHub, `yotta` supports using git and hg URLs directly as well.
For example, to include a privately hosted git repository from example.com:
@@ -47,13 +62,13 @@ For example, to include a privately hosted git repository from example.com:
...
```
-Git URLs support branch, version and tags specifications:
+Git URLs support branch, version, tag and commit specifications:
```
git+ssh://example.com/path/to/repo
-git+ssh://example.com/path/to/repo#<versionspec, branch or tag>
+git+ssh://example.com/path/to/repo#<versionspec, branch, tag or commit>
anything://example.com/path/to/repo.git
-anything://example.com/path/to/repo.git#<versionspec, branch or tag>
+anything://example.com/path/to/repo.git#<versionspec, branch, tag or commit>
```
Currently, mercurial URLs only support a version specification:
diff --git a/yotta/install.py b/yotta/install.py
index 28e2816..1ed7d8a 100644
--- a/yotta/install.py
+++ b/yotta/install.py
@@ -167,7 +167,12 @@ def installComponentAsDependency(args, current_component):
# (if it is not already present), and write that back to disk. Without
# writing to disk the dependency wouldn't be usable.
if installed and not current_component.hasDependency(component_name):
- saved_spec = current_component.saveDependency(installed)
+ vs = sourceparse.parseSourceURL(component_spec)
+ if vs.source_type == 'registry':
+ saved_spec = current_component.saveDependency(installed)
+ else:
+ saved_spec = current_component.saveDependency(installed, component_spec)
+
current_component.writeDescription()
logging.info('dependency %s: %s written to module.json', component_name, saved_spec)
else:
diff --git a/yotta/lib/access.py b/yotta/lib/access.py
index ae8fcac..51dec3b 100644
--- a/yotta/lib/access.py
+++ b/yotta/lib/access.py
@@ -147,8 +147,14 @@ def latestSuitableVersion(name, version_required, registry='modules', quiet=Fals
)
if v:
return v
+
+ # we have passed a specific commit ID:
+ v = remote_component.commitVersion()
+ if v:
+ return v
+
raise access_common.Unavailable(
- 'Github repository "%s" does not have any tags or branches matching "%s"' % (
+ 'Github repository "%s" does not have any tags, branches or commits matching "%s"' % (
version_required, remote_component.tagOrBranchSpec()
)
)
@@ -189,8 +195,14 @@ def latestSuitableVersion(name, version_required, registry='modules', quiet=Fals
)
if v:
return v
+
+ # we have passed a specific commit ID:
+ v = local_clone.commitVersion(remote_component.tagOrBranchSpec())
+ if v:
+ return v
+
raise access_common.Unavailable(
- '%s repository "%s" does not have any tags or branches matching "%s"' % (
+ '%s repository "%s" does not have any tags, branches or commits matching "%s"' % (
clone_type, version_required, spec
)
)
diff --git a/yotta/lib/git_access.py b/yotta/lib/git_access.py
index f53e19f..4b2bbb1 100644
--- a/yotta/lib/git_access.py
+++ b/yotta/lib/git_access.py
@@ -73,8 +73,18 @@ class GitWorkingCopy(object):
def tipVersion(self):
- return GitCloneVersion('', '', self)
+ raise NotImplementedError
+ def commitVersion(self, spec):
+ ''' return a GithubComponentVersion object for a specific commit if valid
+ '''
+ import re
+
+ commit_match = re.match('^[a-f0-9]{7,40}$', spec, re.I)
+ if commit_match:
+ return GitCloneVersion('', spec, self)
+
+ return None
class GitComponent(access_common.RemoteComponent):
def __init__(self, url, tag_or_branch=None, semantic_spec=None):
diff --git a/yotta/lib/github_access.py b/yotta/lib/github_access.py
index e2d47a1..b1f293f 100644
--- a/yotta/lib/github_access.py
+++ b/yotta/lib/github_access.py
@@ -141,6 +141,12 @@ def _getTipArchiveURL(repo):
repo = g.get_repo(repo)
return repo.get_archive_link('tarball')
+@_handleAuth
+def _getCommitArchiveURL(repo, commit):
+ ''' return a string containing a tarball url '''
+ g = Github(settings.getProperty('github', 'authtoken'))
+ repo = g.get_repo(repo)
+ return repo.get_archive_link('tarball', commit)
@_handleAuth
def _getTarball(url, into_directory, cache_key, origin_info=None):
@@ -283,6 +289,19 @@ class GithubComponent(access_common.RemoteComponent):
'', '', _getTipArchiveURL(self.repo), self.name, cache_key=None
)
+ def commitVersion(self):
+ ''' return a GithubComponentVersion object for a specific commit if valid
+ '''
+ import re
+
+ commit_match = re.match('^[a-f0-9]{7,40}$', self.tagOrBranchSpec(), re.I)
+ if commit_match:
+ return GithubComponentVersion(
+ '', '', _getCommitArchiveURL(self.repo, self.tagOrBranchSpec()), self.name, cache_key=None
+ )
+
+ return None
+
@classmethod
def remoteType(cls):
return 'github'
diff --git a/yotta/lib/sourceparse.py b/yotta/lib/sourceparse.py
index 1b1176e..0f451ad 100644
--- a/yotta/lib/sourceparse.py
+++ b/yotta/lib/sourceparse.py
@@ -51,39 +51,55 @@ class VersionSource(object):
return self.semantic_spec.match(v)
-def _splitFragment(url):
- parsed = urlsplit(url)
- if '#' in url:
- return url[:url.index('#')], parsed.fragment
- else:
- return url, None
-
-def _getGithubRef(source_url):
+def _getNonRegistryRef(source_url):
import re
+
# something/something#spec = github
- defragmented, fragment = _splitFragment(source_url)
- github_match = re.match('^[a-z0-9_-]+/([a-z0-9_-]+)$', defragmented, re.I)
+ # something/something@spec = github
+ # something/something spec = github
+ github_match = re.match('^([.a-z0-9_-]+/([.a-z0-9_-]+)) *[@#]?([.a-z0-9_\-\*\^\~\>\<\=]*)$', source_url, re.I)
if github_match:
- return github_match.group(1), VersionSource('github', defragmented, fragment)
+ return github_match.group(2), VersionSource('github', github_match.group(1), github_match.group(3))
- # something/something@spec = github
- alternate_github_match = re.match('([a-z0-9_-]+/([a-z0-9_-]+)) *@?([~^><=.0-9a-z\*-]*)$', source_url, re.I)
- if alternate_github_match:
- return alternate_github_match.group(2), VersionSource('github', alternate_github_match.group(1), alternate_github_match.group(3))
+ parsed = urlsplit(source_url)
+
+ # github
+ if parsed.netloc.endswith('github.com'):
+ # any URL onto github should be fetched over the github API, even if it
+ # would parse as a valid git URL
+ name_match = re.match('^/([.a-z0-9_-]+/([.a-z0-9_-]+?))(.git)?$', parsed.path, re.I)
+ if name_match:
+ return name_match.group(2), VersionSource('github', name_match.group(1), parsed.fragment)
+
+ if '#' in source_url:
+ without_fragment = source_url[:source_url.index('#')]
+ else:
+ without_fragment = source_url
+
+ # git
+ if parsed.scheme.startswith('git+') or parsed.path.endswith('.git'):
+ # git+anything://anything or anything.git is a git repo:
+ name_match = re.match('^.*?([.a-z0-9_-]+?)(.git)?$', parsed.path, re.I)
+ if name_match:
+ return name_match.group(1), VersionSource('git', without_fragment, parsed.fragment)
+
+ # mercurial
+ if parsed.scheme.startswith('hg+') or parsed.path.endswith('.hg'):
+ # hg+anything://anything or anything.hg is a hg repo:
+ name_match = re.match('^.*?([.a-z0-9_-]+?)(.hg)?$', parsed.path, re.I)
+ if name_match:
+ return name_match.group(1), VersionSource('hg', without_fragment, parsed.fragment)
return None, None
+
def parseSourceURL(source_url):
''' Parse the specified version source URL (or version spec), and return an
instance of VersionSource
'''
- import re
- parsed = urlsplit(source_url)
-
- if '#' in source_url:
- without_fragment = source_url[:source_url.index('#')]
- else:
- without_fragment = source_url
+ name, spec = _getNonRegistryRef(source_url)
+ if spec:
+ return spec
try:
url_is_spec = version.Spec(source_url)
@@ -94,22 +110,6 @@ def parseSourceURL(source_url):
# if the url is an unadorned version specification (including an empty
# string) then the source is the module registry:
return VersionSource('registry', '', source_url)
- elif parsed.netloc.endswith('github.com'):
- # any URL onto github should be fetched over the github API, even if it
- # would parse as a valid git URL
- return VersionSource('github', parsed.path, parsed.fragment)
- elif parsed.scheme.startswith('git+') or parsed.path.endswith('.git'):
- # git+anything://anything or anything.git is a git repo:
- return VersionSource('git', without_fragment, parsed.fragment)
- elif parsed.scheme.startswith('hg+') or parsed.path.endswith('.hg'):
- # hg+anything://anything or anything.hg is a hg repo:
- return VersionSource('hg', without_fragment, parsed.fragment)
-
- # something/something@spec = github
- # something/something#spec = github
- module_name, github_match = _getGithubRef(source_url)
- if github_match:
- return github_match
raise InvalidVersionSpec("Invalid version specification: \"%s\"" % (source_url))
@@ -143,8 +143,8 @@ def parseTargetNameAndSpec(target_name_and_spec):
import re
# fist check if this is a raw github specification that we can get the
# target name from:
- name, spec = _getGithubRef(target_name_and_spec)
- if name and spec:
+ name, spec = _getNonRegistryRef(target_name_and_spec)
+ if name:
return name, target_name_and_spec
# next split at the first @ or , if any
@@ -178,8 +178,8 @@ def parseModuleNameAndSpec(module_name_and_spec):
import re
# fist check if this is a raw github specification that we can get the
# module name from:
- name, spec = _getGithubRef(module_name_and_spec)
- if name and spec:
+ name, spec = _getNonRegistryRef(module_name_and_spec)
+ if name:
return name, module_name_and_spec
# next split at the first @, if any
diff --git a/yotta/link.py b/yotta/link.py
index d13263d..8275e4f 100644
--- a/yotta/link.py
+++ b/yotta/link.py
@@ -11,9 +11,6 @@ def addOptions(parser):
)
def tryLink(src, dst):
- # standard library modules, , ,
- import logging
-
# fsutils, , misc filesystem utils, internal
from yotta.lib import fsutils
try:
diff --git a/yotta/link_target.py b/yotta/link_target.py
index e67de6a..0ad10dd 100644
--- a/yotta/link_target.py
+++ b/yotta/link_target.py
@@ -11,9 +11,6 @@ def addOptions(parser):
)
def tryLink(src, dst):
- # standard library modules, , ,
- import logging
-
# fsutils, , misc filesystem utils, internal
from yotta.lib import fsutils
try:
diff --git a/yotta/main.py b/yotta/main.py
index c18cd72..12f6839 100644
--- a/yotta/main.py
+++ b/yotta/main.py
@@ -201,6 +201,7 @@ def main():
short_commands = {
'up':subparser.choices['update'],
'in':subparser.choices['install'],
+ 'un':subparser.choices['uninstall'],
'ln':subparser.choices['link'],
'v':subparser.choices['version'],
'ls':subparser.choices['list'],
|
ARMmbed__yotta-804
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"yotta/lib/sourceparse.py:_getNonRegistryRef"
],
"edited_modules": [
"yotta/lib/sourceparse.py:_getNonRegistryRef"
]
},
"file": "yotta/lib/sourceparse.py"
}
] |
ARMmbed/yotta
|
4094b7a26c66dd64ff724d4f72da282d41ea9fca
|
Semver incompatibility
Hi,
It seems the recent version has broken semantic version for any previous version, which we heavily use in our project, [microbit-dal](https://github.com/lancaster-university/microbit-dal).
We have had two new users on v18 who have reported this breakage: https://github.com/lancaster-university/microbit-dal/issues/282
Any help would be greatly appreciated :smile:
|
diff --git a/yotta/lib/sourceparse.py b/yotta/lib/sourceparse.py
index 0f451ad..eb1f0b4 100644
--- a/yotta/lib/sourceparse.py
+++ b/yotta/lib/sourceparse.py
@@ -57,7 +57,7 @@ def _getNonRegistryRef(source_url):
# something/something#spec = github
# something/something@spec = github
# something/something spec = github
- github_match = re.match('^([.a-z0-9_-]+/([.a-z0-9_-]+)) *[@#]?([.a-z0-9_\-\*\^\~\>\<\=]*)$', source_url, re.I)
+ github_match = re.match(r'^([.a-z0-9_-]+/([.a-z0-9_-]+)) *[@#]?([^/:\?\[\\]*)$', source_url, re.I)
if github_match:
return github_match.group(2), VersionSource('github', github_match.group(1), github_match.group(3))
|
ASFHyP3__hyp3-autorift-202
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"hyp3_autorift/io.py:write_geospatial"
],
"edited_modules": [
"hyp3_autorift/io.py:write_geospatial"
]
},
"file": "hyp3_autorift/io.py"
},
{
"changes": {
"added_entities": [
"hyp3_autorift/process.py:_apply_filter_function"
],
"added_modules": [
"hyp3_autorift/process.py:_apply_filter_function"
],
"edited_entities": [
"hyp3_autorift/process.py:create_filtered_filepath",
"hyp3_autorift/process.py:apply_landsat_filtering",
"hyp3_autorift/process.py:process"
],
"edited_modules": [
"hyp3_autorift/process.py:create_filtered_filepath",
"hyp3_autorift/process.py:apply_landsat_filtering",
"hyp3_autorift/process.py:process"
]
},
"file": "hyp3_autorift/process.py"
}
] |
ASFHyP3/hyp3-autorift
|
ca9bda5f0a8a5db47d0d83c825a9d447a6c4180e
|
Landsat 7 + 8 pairs may not be handled well
Since we only look at the reference scene to [determine the platform](https://github.com/ASFHyP3/hyp3-autorift/blob/develop/hyp3_autorift/process.py#L319), we may have some issues with the secondary scene:
- [x] L7 reference scene w/ a L8 secondary will attempt to apply the Wallis filter and bonk:
https://github.com/ASFHyP3/hyp3-autorift/blob/develop/hyp3_autorift/process.py#L269-L282
- [x] L8 reference scene w/ a L7 secondary will not have the Wallis filter applied to it:
https://github.com/ASFHyP3/hyp3-autorift/blob/develop/hyp3_autorift/process.py#L368-L370
Fortunately, in our current campaign pair list, 4/5 pairs are only crossed with 4/5 pairs, and 9 pairs are only crossed with 8, so we should only see issues around 7+8 pairs.
```python
>>> import geopandas as gpd
>>> df = gpd.read_parquet('l45789.parquet')
>>> df.groupby(['ref_mission', 'sec_mission']).reference.count()
ref_mission sec_mission
L4 L4 1058
L5 3203
L5 L4 2988
L5 767024
L7 L7 2003704
L8 474339
L8 L7 416539
L8 4103107
L9 367178
L9 L8 112403
L9 109936
```
**Fix:** AutoRIFT pre-processing defaults to the strictest filtering, so we should allow L8 scenes to be wallis filled if either pair is L7. And we should check both ref, sec platform when deciding to run the pre-processing filters or not in `process.py`
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e092e35..a9108fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ and this project adheres to [PEP 440](https://www.python.org/dev/peps/pep-0440/)
and uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.10.4]
+
+### Fixed
+* Landsat 7+8 pairs will be filtered appropriately; see [#201](https://github.com/ASFHyP3/hyp3-autorift/issues/201)
+
## [0.10.3]
### Added
diff --git a/hyp3_autorift/io.py b/hyp3_autorift/io.py
index d7a1b22..9876b6d 100644
--- a/hyp3_autorift/io.py
+++ b/hyp3_autorift/io.py
@@ -168,7 +168,7 @@ def load_geospatial(infile: str, band: int = 1):
def write_geospatial(outfile: str, data, transform, projection, nodata,
- driver: str = 'GTiff', dtype: int = gdal.GDT_Float64):
+ driver: str = 'GTiff', dtype: int = gdal.GDT_Float64) -> str:
driver = gdal.GetDriverByName(driver)
rows, cols = data.shape
diff --git a/hyp3_autorift/process.py b/hyp3_autorift/process.py
index a56b7f6..b887d5e 100644
--- a/hyp3_autorift/process.py
+++ b/hyp3_autorift/process.py
@@ -11,7 +11,7 @@ import xml.etree.ElementTree as ET
from datetime import datetime
from pathlib import Path
from secrets import token_hex
-from typing import Optional, Tuple
+from typing import Callable, Optional, Tuple
import boto3
import botocore.exceptions
@@ -227,12 +227,11 @@ def get_s1_primary_polarization(granule_name):
raise ValueError(f'Cannot determine co-polarization of granule {granule_name}')
-def create_filtered_filepath(path: str):
+def create_filtered_filepath(path: str) -> Path:
parent = (Path.cwd() / 'filtered').resolve()
parent.mkdir(exist_ok=True)
- out_path = parent / Path(path).name
- return str(out_path)
+ return parent / Path(path).name
def prepare_array_for_filtering(array: np.ndarray, nodata: int) -> Tuple[np.ndarray, np.ndarray]:
@@ -266,32 +265,52 @@ def apply_wallis_nodata_fill_filter(array: np.ndarray, nodata: int) -> Tuple[np.
return filtered, zero_mask
-def apply_landsat_filtering(image_path: str, image_platform: str) -> Tuple[Path, Optional[Path]]:
+def _apply_filter_function(image_path: str, filter_function: Callable) -> Tuple[Path, Optional[Path]]:
image_array, image_transform, image_projection, image_nodata = io.load_geospatial(image_path)
image_array = image_array.astype(np.float32)
+ image_filtered, zero_mask = filter_function(image_array, image_nodata)
+
+ image_new_path = create_filtered_filepath(image_path)
+ _ = io.write_geospatial(str(image_new_path), image_filtered, image_transform, image_projection,
+ nodata=0, dtype=gdal.GDT_Float32)
+
+ zero_path = None
+ if zero_mask is not None:
+ zero_path = create_filtered_filepath(f'{image_new_path.stem}_zeroMask{image_new_path.suffix}')
+ _ = io.write_geospatial(str(zero_path), zero_mask, image_transform, image_projection,
+ nodata=np.iinfo(np.uint8).max, dtype=gdal.GDT_Byte)
+
+ return image_new_path, zero_path
+
+
+def apply_landsat_filtering(reference: str, secondary: str) -> Tuple[Path, Optional[Path], Path, Optional[Path]]:
+ reference_platform = get_platform(reference)
+ secondary_platform = get_platform(secondary)
+ if reference_platform > 'L7' and secondary_platform > 'L7':
+ raise NotImplementedError(
+ f'{reference_platform}+{secondary_platform} pairs should be highpass filtered in autoRIFT instead'
+ )
+
platform_filter_dispatch = {
'L4': apply_fft_filter,
'L5': apply_fft_filter,
'L7': apply_wallis_nodata_fill_filter,
+ 'L8': apply_wallis_nodata_fill_filter, # sometimes paired w/ L7 scenes, so use same filter
}
-
try:
- image_filtered, zero_mask = platform_filter_dispatch[image_platform](image_array, image_nodata)
+ reference_filter = platform_filter_dispatch[reference_platform]
+ secondary_filter = platform_filter_dispatch[secondary_platform]
except KeyError:
- raise NotImplementedError(f'Unknown pre-processing filter for satellite platform: {image_platform}')
+ raise NotImplementedError('Unknown pre-processing filter for satellite platform')
- image_new_path = create_filtered_filepath(image_path)
- image_path = io.write_geospatial(image_new_path, image_filtered, image_transform, image_projection,
- nodata=0, dtype=gdal.GDT_Float32)
+ if reference_filter != secondary_filter:
+ raise NotImplementedError('AutoRIFT not available for image pairs with different preprocessing methods')
- zero_path = None
- if zero_mask is not None:
- zero_path = create_filtered_filepath(f'{Path(image_path).stem}_zeroMask{Path(image_path).suffix}')
- _ = io.write_geospatial(str(zero_path), zero_mask, image_transform, image_projection,
- nodata=np.iinfo(np.uint8).max, dtype=gdal.GDT_Byte)
+ reference_path, reference_zero_path = _apply_filter_function(reference, reference_filter)
+ secondary_path, secondary_zero_path = _apply_filter_function(secondary, secondary_filter)
- return image_path, zero_path
+ return reference_path, reference_zero_path, secondary_path, secondary_zero_path
def process(reference: str, secondary: str, parameter_file: str = DEFAULT_PARAMETER_FILE,
@@ -365,9 +384,10 @@ def process(reference: str, secondary: str, parameter_file: str = DEFAULT_PARAME
secondary_metadata = get_lc2_metadata(secondary)
secondary_path = get_lc2_path(secondary_metadata)
- if platform in ('L4', 'L5', 'L7'):
- reference_path, reference_zero_path = apply_landsat_filtering(reference_path, platform)
- secondary_path, secondary_zero_path = apply_landsat_filtering(secondary_path, platform)
+ filter_platform = min([platform, get_platform(secondary)])
+ if filter_platform in ('L4', 'L5', 'L7'):
+ reference_path, reference_zero_path, secondary_path, secondary_zero_path = \
+ apply_landsat_filtering(reference_path, secondary_path)
if reference_metadata['properties']['proj:epsg'] != secondary_metadata['properties']['proj:epsg']:
log.info('Reference and secondary projections are different! Reprojecting.')
@@ -376,9 +396,6 @@ def process(reference: str, secondary: str, parameter_file: str = DEFAULT_PARAME
if reference_zero_path and secondary_zero_path:
_, _ = io.ensure_same_projection(reference_zero_path, secondary_zero_path)
- elif not isinstance(reference_zero_path, type(secondary_zero_path)):
- raise NotImplementedError('AutoRIFT not available for image pairs with different preprocessing methods')
-
reference_path, secondary_path = io.ensure_same_projection(reference_path, secondary_path)
bbox = reference_metadata['bbox']
|
ASFHyP3__hyp3-autorift-49
|
[
{
"changes": {
"added_entities": [
"hyp3_autorift/geometry.py:poly_bounds_in_proj"
],
"added_modules": [
"hyp3_autorift/geometry.py:poly_bounds_in_proj"
],
"edited_entities": [
"hyp3_autorift/geometry.py:polygon_from_bbox",
"hyp3_autorift/geometry.py:find_jpl_dem"
],
"edited_modules": [
"hyp3_autorift/geometry.py:polygon_from_bbox",
"hyp3_autorift/geometry.py:find_jpl_dem"
]
},
"file": "hyp3_autorift/geometry.py"
},
{
"changes": {
"added_entities": [
"hyp3_autorift/io.py:find_jpl_dem",
"hyp3_autorift/io.py:subset_jpl_tifs"
],
"added_modules": [
"hyp3_autorift/io.py:find_jpl_dem",
"hyp3_autorift/io.py:subset_jpl_tifs"
],
"edited_entities": [
"hyp3_autorift/io.py:_download_s3_files",
"hyp3_autorift/io.py:_get_s3_keys_for_dem",
"hyp3_autorift/io.py:fetch_jpl_tifs"
],
"edited_modules": [
"hyp3_autorift/io.py:_download_s3_files",
"hyp3_autorift/io.py:_get_s3_keys_for_dem",
"hyp3_autorift/io.py:fetch_jpl_tifs"
]
},
"file": "hyp3_autorift/io.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"hyp3_autorift/process.py:process"
],
"edited_modules": [
"hyp3_autorift/process.py:process"
]
},
"file": "hyp3_autorift/process.py"
}
] |
ASFHyP3/hyp3-autorift
|
cf8c6dadd1d4af9cb310a2eb470ac0c2e820c2ab
|
Get associated autoRIFT files from parameter shapefile
Currently, we hardcode the set of needed files for processing:
https://github.com/ASFHyP3/hyp3-autorift/blob/develop/hyp3_autorift/io.py#L47-L68
These however, at detailed in the new parameter shapefile and could be pulled from there instead to be more flexible to future change (see #47 )
|
diff --git a/hyp3_autorift/geometry.py b/hyp3_autorift/geometry.py
index 5b66d76..a2c6a13 100644
--- a/hyp3_autorift/geometry.py
+++ b/hyp3_autorift/geometry.py
@@ -2,19 +2,18 @@
import logging
import os
+from typing import Tuple
import isce # noqa: F401
import isceobj
import numpy as np
from contrib.demUtils import createDemStitcher
from contrib.geo_autoRIFT.geogrid import Geogrid
-from hyp3lib import DemError
from isceobj.Orbit.Orbit import Orbit
from isceobj.Sensor.TOPS.Sentinel1 import Sentinel1
from osgeo import gdal
from osgeo import ogr
-
-from hyp3_autorift.io import AUTORIFT_PREFIX, ITS_LIVE_BUCKET
+from osgeo import osr
log = logging.getLogger(__name__)
@@ -89,7 +88,7 @@ def bounding_box(safe, priority='reference', polarization='hh', orbits='Orbits',
return lat_limits, lon_limits
-def polygon_from_bbox(lat_limits, lon_limits):
+def polygon_from_bbox(lat_limits: Tuple[float, float], lon_limits: Tuple[float, float]) -> ogr.Geometry:
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(lon_limits[0], lat_limits[0])
ring.AddPoint(lon_limits[1], lat_limits[0])
@@ -101,20 +100,24 @@ def polygon_from_bbox(lat_limits, lon_limits):
return polygon
-def find_jpl_dem(lat_limits, lon_limits):
- shape_file = f'/vsicurl/http://{ITS_LIVE_BUCKET}.s3.amazonaws.com/{AUTORIFT_PREFIX}/autorift_parameters.shp'
- driver = ogr.GetDriverByName('ESRI Shapefile')
- shapes = driver.Open(shape_file, gdal.GA_ReadOnly)
+def poly_bounds_in_proj(polygon: ogr.Geometry, in_epsg: int, out_epsg: int):
+ in_srs = osr.SpatialReference()
+ in_srs.ImportFromEPSG(in_epsg)
- centroid = polygon_from_bbox(lat_limits, lon_limits).Centroid()
- for feature in shapes.GetLayer(0):
- if feature.geometry().Contains(centroid):
- return f'{feature["name"]}_0240m'
+ out_srs = osr.SpatialReference()
+ out_srs.ImportFromEPSG(out_epsg)
- raise DemError('Could not determine appropriate DEM for:\n'
- f' lat (min, max): {lat_limits}'
- f' lon (min, max): {lon_limits}'
- f' using: {shape_file}')
+ transformation = osr.CoordinateTransformation(in_srs, out_srs)
+ ring = ogr.Geometry(ogr.wkbLinearRing)
+ for point in polygon.GetBoundary().GetPoints():
+ try:
+ lon, lat = point
+ except ValueError:
+ # buffered polygons only have (X, Y) while unbuffered have (X, Y, Z)
+ lon, lat, _ = point
+ ring.AddPoint(*transformation.TransformPoint(lat, lon))
+
+ return ring.GetEnvelope()
def prep_isce_dem(input_dem, lat_limits, lon_limits, isce_dem=None):
diff --git a/hyp3_autorift/io.py b/hyp3_autorift/io.py
index 226f3d6..b38fa23 100644
--- a/hyp3_autorift/io.py
+++ b/hyp3_autorift/io.py
@@ -3,24 +3,24 @@
import argparse
import logging
import os
-import shutil
import textwrap
from pathlib import Path
from typing import Union
import boto3
-from boto3.s3.transfer import TransferConfig
-from botocore import UNSIGNED
-from botocore.config import Config
+from hyp3lib import DemError
from isce.applications.topsApp import TopsInSAR
+from osgeo import gdal
+from osgeo import ogr
from scipy.io import savemat
+from hyp3_autorift.geometry import poly_bounds_in_proj
+
log = logging.getLogger(__name__)
ITS_LIVE_BUCKET = 'its-live-data.jpl.nasa.gov'
AUTORIFT_PREFIX = 'autorift_parameters/v001'
-_s3_client_unsigned = boto3.client('s3', config=Config(signature_version=UNSIGNED))
_s3_client = boto3.client('s3')
@@ -31,53 +31,65 @@ def download_s3_file_requester_pays(target_path: Union[str, Path], bucket: str,
return filename
-def _download_s3_files(target_dir, bucket, keys, chunk_size=50*1024*1024):
- transfer_config = TransferConfig(multipart_threshold=chunk_size, multipart_chunksize=chunk_size)
- file_list = []
- for key in keys:
- filename = os.path.join(target_dir, os.path.basename(key))
- if os.path.exists(filename):
- continue
- file_list.append(filename)
- log.info(f'Downloading s3://{bucket}/{key} to {filename}')
- _s3_client_unsigned.download_file(Bucket=bucket, Key=key, Filename=filename, Config=transfer_config)
- return file_list
-
-
-def _get_s3_keys_for_dem(prefix=AUTORIFT_PREFIX, dem='GRE240m'):
- tags = [
- 'h',
- 'StableSurface',
- 'dhdx',
- 'dhdy',
- 'dhdxs',
- 'dhdys',
- 'vx0',
- 'vy0',
- 'vxSearchRange',
- 'vySearchRange',
- 'xMinChipSize',
- 'yMinChipSize',
- 'xMaxChipSize',
- 'yMaxChipSize',
- # FIXME: Was renamed from masks to sp by JPL; change hasn't been propagated to autoRIFT
- # keep last so we can easily rename the file after downloading
- 'sp',
- ]
- keys = [f'{prefix}/{dem}_{tag}.tif' for tag in tags]
- return keys
-
-
-def fetch_jpl_tifs(dem='GRE240m', target_dir='DEM', bucket=ITS_LIVE_BUCKET, prefix=AUTORIFT_PREFIX):
- # FIXME: gdalwarp needed subset instead?
- log.info(f"Downloading {dem} tifs from JPL's AWS bucket")
-
- for logger in ('botocore', 's3transfer'):
- logging.getLogger(logger).setLevel(logging.WARNING)
-
- keys = _get_s3_keys_for_dem(prefix, dem)
- tifs = _download_s3_files(target_dir, bucket, keys)
- shutil.move(tifs[-1], tifs[-1].replace('_sp.tif', '_masks.tif'))
+def find_jpl_dem(polygon: ogr.Geometry) -> dict:
+ shape_file = f'/vsicurl/http://{ITS_LIVE_BUCKET}.s3.amazonaws.com/{AUTORIFT_PREFIX}/autorift_parameters.shp'
+ driver = ogr.GetDriverByName('ESRI Shapefile')
+ shapes = driver.Open(shape_file, gdal.GA_ReadOnly)
+
+ centroid = polygon.Centroid()
+ for feature in shapes.GetLayer(0):
+ if feature.geometry().Contains(centroid):
+ dem_info = {
+ 'name': f'{feature["name"]}_0240m',
+ 'epsg': feature['epsg'],
+ 'tifs': {
+ 'h': f"/vsicurl/{feature['h']}",
+ 'StableSurface': f"/vsicurl/{feature['StableSurfa']}",
+ 'dhdx': f"/vsicurl/{feature['dhdx']}",
+ 'dhdy': f"/vsicurl/{feature['dhdy']}",
+ 'dhdxs': f"/vsicurl/{feature['dhdxs']}",
+ 'dhdys': f"/vsicurl/{feature['dhdys']}",
+ 'vx0': f"/vsicurl/{feature['vx0']}",
+ 'vy0': f"/vsicurl/{feature['vy0']}",
+ 'vxSearchRange': f"/vsicurl/{feature['vxSearchRan']}",
+ 'vySearchRange': f"/vsicurl/{feature['vySearchRan']}",
+ 'xMinChipSize': f"/vsicurl/{feature['xMinChipSiz']}",
+ 'yMinChipSize': f"/vsicurl/{feature['yMinChipSiz']}",
+ 'xMaxChipSize': f"/vsicurl/{feature['xMaxChipSiz']}",
+ 'yMaxChipSize': f"/vsicurl/{feature['yMaxChipSiz']}",
+ 'sp': f"/vsicurl/{feature['sp']}",
+ },
+ }
+ return dem_info
+
+ raise DemError('Could not determine appropriate DEM for:\n'
+ f' centroid: {centroid}'
+ f' using: {shape_file}')
+
+
+def subset_jpl_tifs(polygon: ogr.Geometry, buffer: float = 0.15, target_dir: Union[str, Path] = '.'):
+ dem_info = find_jpl_dem(polygon)
+ log.info(f'Subsetting {dem_info["name"]} tifs from s3://{ITS_LIVE_BUCKET}/{AUTORIFT_PREFIX}/')
+
+ min_x, max_x, min_y, max_y = poly_bounds_in_proj(polygon.Buffer(buffer), in_epsg=4326, out_epsg=dem_info['epsg'])
+ output_bounds = (min_x, min_y, max_x, max_y)
+ log.debug(f'Subset bounds: {output_bounds}')
+
+ subset_tifs = {}
+ for key, tif in dem_info['tifs'].items():
+ out_path = os.path.join(target_dir, os.path.basename(tif))
+
+ # FIXME: shouldn't need to do after next autoRIFT upgrade
+ if out_path.endswith('_sp.tif'):
+ out_path = out_path.replace('_sp.tif', '_masks.tif')
+
+ subset_tifs[key] = out_path
+
+ gdal.Warp(
+ out_path, tif, outputBounds=output_bounds, xRes=240, yRes=240, targetAlignedPixels=True, multithread=True,
+ )
+
+ return subset_tifs
def format_tops_xml(reference, secondary, polarization, dem, orbits, xml_file='topsApp.xml'):
diff --git a/hyp3_autorift/process.py b/hyp3_autorift/process.py
index 401bd34..d3d3936 100644
--- a/hyp3_autorift/process.py
+++ b/hyp3_autorift/process.py
@@ -196,25 +196,22 @@ def process(reference: str, secondary: str, polarization: str = 'hh', band: str
lat_limits = (bbox[1], bbox[3])
lon_limits = (bbox[0], bbox[2])
- dem = geometry.find_jpl_dem(lat_limits, lon_limits)
- dem_dir = os.path.join(os.getcwd(), 'DEM')
- mkdir_p(dem_dir)
- io.fetch_jpl_tifs(dem=dem, target_dir=dem_dir)
- dem_prefix = os.path.join(dem_dir, dem)
-
- geogrid_parameters = f'-d {dem_prefix}_h.tif -ssm {dem_prefix}_StableSurface.tif ' \
- f'-sx {dem_prefix}_dhdx.tif -sy {dem_prefix}_dhdy.tif ' \
- f'-vx {dem_prefix}_vx0.tif -vy {dem_prefix}_vy0.tif ' \
- f'-srx {dem_prefix}_vxSearchRange.tif -sry {dem_prefix}_vySearchRange.tif ' \
- f'-csminx {dem_prefix}_xMinChipSize.tif -csminy {dem_prefix}_yMinChipSize.tif ' \
- f'-csmaxx {dem_prefix}_xMaxChipSize.tif -csmaxy {dem_prefix}_yMaxChipSize.tif'
+ scene_poly = geometry.polygon_from_bbox(lat_limits, lon_limits)
+ tifs = io.subset_jpl_tifs(scene_poly, target_dir=Path.cwd())
+
+ geogrid_parameters = f'-d {tifs["h"]} -ssm {tifs["StableSurface"]} ' \
+ f'-sx {tifs["dhdx"]} -sy {tifs["dhdy"]} ' \
+ f'-vx {tifs["vx0"]} -vy {tifs["vy0"]} ' \
+ f'-srx {tifs["vxSearchRange"]} -sry {tifs["vySearchRange"]} ' \
+ f'-csminx {tifs["xMinChipSize"]} -csminy {tifs["yMinChipSize"]} ' \
+ f'-csmaxx {tifs["xMaxChipSize"]} -csmaxy {tifs["yMaxChipSize"]}'
autorift_parameters = '-g window_location.tif -o window_offset.tif -sr window_search_range.tif ' \
'-csmin window_chip_size_min.tif -csmax window_chip_size_max.tif ' \
'-vx window_rdr_off2vel_x_vec.tif -vy window_rdr_off2vel_y_vec.tif ' \
'-ssm window_stable_surface_mask.tif'
if platform == 'S1':
- isce_dem = geometry.prep_isce_dem(f'{dem_prefix}_h.tif', lat_limits, lon_limits)
+ isce_dem = geometry.prep_isce_dem(tifs["h"], lat_limits, lon_limits)
io.format_tops_xml(reference, secondary, polarization, isce_dem, orbits)
diff --git a/setup.py b/setup.py
index 54a17a4..96de391 100644
--- a/setup.py
+++ b/setup.py
@@ -62,7 +62,6 @@ setup(
'testGeogrid_ISCE.py = hyp3_autorift.vend.testGeogrid_ISCE:main',
'testautoRIFT.py = hyp3_autorift.vend.testautoRIFT:main',
'testGeogridOptical.py = hyp3_autorift.vend.testGeogridOptical:main',
- # FIXME: Only needed for testautoRIFT.py and testautoRIFT_ISCE.py
'topsinsar_filename.py = hyp3_autorift.io:topsinsar_mat',
]
},
|
ASFHyP3__hyp3-sdk-152
|
[
{
"changes": {
"added_entities": [
"hyp3_sdk/jobs.py:Batch.__eq__"
],
"added_modules": null,
"edited_entities": [
"hyp3_sdk/jobs.py:Batch.__delitem__",
"hyp3_sdk/jobs.py:Batch.__reverse__",
"hyp3_sdk/jobs.py:Batch.__getitem__"
],
"edited_modules": [
"hyp3_sdk/jobs.py:Batch"
]
},
"file": "hyp3_sdk/jobs.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"hyp3_sdk/util.py:download_file"
],
"edited_modules": [
"hyp3_sdk/util.py:download_file"
]
},
"file": "hyp3_sdk/util.py"
}
] |
ASFHyP3/hyp3-sdk
|
b3e64fdef9d76d7abb6bd762ae1b8429ebd1e3f5
|
slicing a Batch returns a list
Should return a Batch instead.
```
>>> import hyp3_sdk
>>> hyp3 = hyp3_sdk.HyP3()
>>> jobs = hyp3.find_jobs()
>>> type(jobs)
<class 'hyp3_sdk.jobs.Batch'>
>>> len(jobs)
955
>>> type(jobs[3:10])
<class 'list'>
```
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c340f0..55972fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,14 @@ and this project adheres to [PEP 440](https://www.python.org/dev/peps/pep-0440/)
and uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.4.1](https://github.com/ASFHyP3/hyp3-sdk/compare/v1.4.1...v1.4.1)
+
+### Fixed
+- Slicing a `Batch` object will now return a new `Batch` instead of `list` of jobs
+- `Batch` equality now compares the contained jobs and not object identity
+
## [1.4.0](https://github.com/ASFHyP3/hyp3-sdk/compare/v1.3.2...v1.4.0)
+
### Added
- Exposed new `include_displacement_maps` parameter for `HyP3.prepare_insar_job` and `HyP3.submit_insar_job`, which will
cause both a line-of-sight displacement and a vertical displacement GeoTIFF to be included in the product.
diff --git a/hyp3_sdk/jobs.py b/hyp3_sdk/jobs.py
index fbe31e8..dbcfb4d 100644
--- a/hyp3_sdk/jobs.py
+++ b/hyp3_sdk/jobs.py
@@ -170,21 +170,22 @@ class Batch:
def __contains__(self, job: Job):
return job in self.jobs
- def __delitem__(self, job: Job):
+ def __eq__(self, other: 'Batch'):
+ return self.jobs == other.jobs
+
+ def __delitem__(self, job: int):
self.jobs.pop(job)
return self
def __getitem__(self, index: int):
+ if isinstance(index, slice):
+ return Batch(self.jobs[index])
return self.jobs[index]
def __setitem__(self, index: int, job: Job):
self.jobs[index] = job
return self
- def __reverse__(self):
- for job in self.jobs[::-1]:
- yield job
-
def __repr__(self):
reprs = ", ".join([job.__repr__() for job in self.jobs])
return f'Batch([{reprs}])'
diff --git a/hyp3_sdk/util.py b/hyp3_sdk/util.py
index 94ab7a7..cae1eac 100644
--- a/hyp3_sdk/util.py
+++ b/hyp3_sdk/util.py
@@ -109,8 +109,8 @@ def download_file(url: str, filepath: Union[Path, str], chunk_size=None, retries
session.mount('https://', HTTPAdapter(max_retries=retry_strategy))
session.mount('http://', HTTPAdapter(max_retries=retry_strategy))
-
- with session.get(url, stream=True) as s:
+ stream = False if chunk_size is None else True
+ with session.get(url, stream=stream) as s:
s.raise_for_status()
tqdm = get_tqdm_progress_bar()
with tqdm.wrapattr(open(filepath, "wb"), 'write', miniters=1, desc=filepath.name,
|
ASFHyP3__hyp3-sdk-51
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"hyp3_sdk/hyp3.py:HyP3.__init__"
],
"edited_modules": [
"hyp3_sdk/hyp3.py:HyP3"
]
},
"file": "hyp3_sdk/hyp3.py"
}
] |
ASFHyP3/hyp3-sdk
|
67e33235f7dc3b98241fe34d97a4fae58873590c
|
Add custom User Agent header to hyp3 api session
e.g. `User-Agent: hyp3-sdk v0.1.2` so we can identify SDK-generated requests in the API access logs, separate from other requests made via `requests`.
|
diff --git a/hyp3_sdk/hyp3.py b/hyp3_sdk/hyp3.py
index 7d90095..baf69f4 100644
--- a/hyp3_sdk/hyp3.py
+++ b/hyp3_sdk/hyp3.py
@@ -6,6 +6,7 @@ from urllib.parse import urljoin
from requests.exceptions import HTTPError, RequestException
+import hyp3_sdk
from hyp3_sdk.exceptions import HyP3Error, ValidationError
from hyp3_sdk.jobs import Batch, Job
from hyp3_sdk.util import get_authenticated_session
@@ -28,6 +29,7 @@ class HyP3:
"""
self.url = api_url
self.session = get_authenticated_session(username, password)
+ self.session.headers.update({'User-Agent': f'{hyp3_sdk.__name__}/{hyp3_sdk.__version__}'})
def find_jobs(self, start: Optional[datetime] = None, end: Optional[datetime] = None,
status: Optional[str] = None, name: Optional[str] = None) -> Batch:
|
ASFHyP3__hyp3-sdk-53
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"hyp3_sdk/jobs.py:Batch.__init__"
],
"edited_modules": [
"hyp3_sdk/jobs.py:Batch"
]
},
"file": "hyp3_sdk/jobs.py"
}
] |
ASFHyP3/hyp3-sdk
|
56cfb700341a0de44ee0f2f3548d5ed6c534d659
|
Batch constructor should create an empty batch by default
Currently, calling `jobs = Batch()` raises `TypeError: __init__() missing 1 required positional argument: 'jobs'`.
To construct an empty batch, the user has to write `jobs = Batch([])`. It would be more intuitive if this were the default behavior without having to explicitly provide an empty list.
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8905268..ddcacaa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [PEP 440](https://www.python.org/dev/peps/pep-0440/)
and uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.3.3](https://github.com/ASFHyP3/hyp3-sdk/compare/v0.3.2...v0.3.3)
+### Added
+- SDK will attach a `User-Agent` statement like `hyp3_sdk/VERSION` to all API interactions
+
+### Changed
+- Providing a job list to `Batch.__init__()` is now optional; an empty batch will
+ be created if the job list is not provided
+- `Batch.__init__()` no longer issues a warning when creating an empty batch
## [0.3.2](https://github.com/ASFHyP3/hyp3-sdk/compare/v0.3.1...v0.3.2)
### Changed
diff --git a/hyp3_sdk/jobs.py b/hyp3_sdk/jobs.py
index fbe8837..7866439 100644
--- a/hyp3_sdk/jobs.py
+++ b/hyp3_sdk/jobs.py
@@ -1,4 +1,3 @@
-import warnings
from datetime import datetime
from pathlib import Path
from typing import List, Optional, Union
@@ -124,10 +123,9 @@ class Job:
class Batch:
- def __init__(self, jobs: List[Job]):
- if len(jobs) == 0:
- warnings.warn('Jobs list is empty; creating an empty Batch', UserWarning)
-
+ def __init__(self, jobs: Optional[List[Job]] = None):
+ if jobs is None:
+ jobs = []
self.jobs = jobs
def __len__(self):
|
ASFHyP3__hyp3-sdk-70
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"hyp3_sdk/exceptions.py:ValidationError"
]
},
"file": "hyp3_sdk/exceptions.py"
},
{
"changes": {
"added_entities": [
"hyp3_sdk/hyp3.py:HyP3.submit_prepared_jobs",
"hyp3_sdk/hyp3.py:HyP3.prepare_autorift_job",
"hyp3_sdk/hyp3.py:HyP3.prepare_rtc_job",
"hyp3_sdk/hyp3.py:HyP3.prepare_insar_job"
],
"added_modules": null,
"edited_entities": [
"hyp3_sdk/hyp3.py:HyP3.submit_job_dict",
"hyp3_sdk/hyp3.py:HyP3.submit_autorift_job",
"hyp3_sdk/hyp3.py:HyP3.submit_rtc_job",
"hyp3_sdk/hyp3.py:HyP3.submit_insar_job"
],
"edited_modules": [
"hyp3_sdk/hyp3.py:HyP3"
]
},
"file": "hyp3_sdk/hyp3.py"
}
] |
ASFHyP3/hyp3-sdk
|
6e4004e372771dc444bf5f334f1f8e25a39313bf
|
use fewer requests when submitting multiple jobs
When submitting large jobs, multiple api request are created, would be nice for a way to aggrigate jobs into one request
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2ef243f..620eb3f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [PEP 440](https://www.python.org/dev/peps/pep-0440/)
and uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [unreleased]
+
+### Added
+- Methods to prepare jobs for submission to HyP3
+ - `HyP3.prepare_autorift_job`
+ - `HyP3.prepare_rtc_job`
+ - `HyP3.prepare_insar_job`
+
+### Changed
+- HyP3 submit methods will always return a `Batch` containing the submitted job(s)
+- `HyP3.submit_job_dict` has been renamed to `HyP3.submit_prepared_jobs` and can
+ submit one or more prepared job dictionaries.
+
## [0.4.0](https://github.com/ASFHyP3/hyp3-sdk/compare/v0.3.3...v0.4.0)
### Added
diff --git a/conda-env.yml b/conda-env.yml
index 19264fd..60e7b10 100644
--- a/conda-env.yml
+++ b/conda-env.yml
@@ -5,6 +5,10 @@ channels:
dependencies:
- pip
# For packaging, and testing
+ - flake8
+ - flake8-import-order
+ - flake8-blind-except
+ - flake8-builtins
- setuptools
- setuptools_scm
- wheel
@@ -18,4 +22,3 @@ dependencies:
- pip:
# For packaging and testing
- s3pypi
- - safety
diff --git a/hyp3_sdk/exceptions.py b/hyp3_sdk/exceptions.py
index eeb5f3f..3c1fac5 100644
--- a/hyp3_sdk/exceptions.py
+++ b/hyp3_sdk/exceptions.py
@@ -5,9 +5,5 @@ class HyP3Error(Exception):
"""Base Exception for Hyp3_sdk"""
-class ValidationError(HyP3Error):
- """Raise when jobs do not pass validation"""
-
-
class AuthenticationError(HyP3Error):
"""Raise when authentication does not succeed"""
diff --git a/hyp3_sdk/hyp3.py b/hyp3_sdk/hyp3.py
index 8f85510..3acd82e 100644
--- a/hyp3_sdk/hyp3.py
+++ b/hyp3_sdk/hyp3.py
@@ -2,13 +2,13 @@ import time
import warnings
from datetime import datetime, timedelta
from functools import singledispatchmethod
-from typing import Optional, Union
+from typing import List, Optional, Union
from urllib.parse import urljoin
from requests.exceptions import HTTPError, RequestException
import hyp3_sdk
-from hyp3_sdk.exceptions import HyP3Error, ValidationError
+from hyp3_sdk.exceptions import HyP3Error
from hyp3_sdk.jobs import Batch, Job
from hyp3_sdk.util import get_authenticated_session
@@ -105,7 +105,7 @@ class HyP3:
job_or_batch: A Batch of Job object to refresh
Returns:
- obj: A Batch or Job object with refreshed information
+ A Batch or Job object with refreshed information
"""
raise NotImplementedError(f'Cannot refresh {type(job_or_batch)} type object')
@@ -120,71 +120,134 @@ class HyP3:
def _refresh_job(self, job: Job):
return self._get_job_by_id(job.job_id)
- def submit_job_dict(self, job_dict: dict, name: Optional[str] = None, validate_only: bool = False) -> Job:
- if name is not None:
- if len(name) > 20:
- raise ValidationError('Job name too long; must be less than 20 characters')
- job_dict['name'] = name
+ def submit_prepared_jobs(self, prepared_jobs: Union[dict, List[dict]]) -> Batch:
+ """Submit a prepared job dictionary, or list of prepared job dictionaries
+
+ Args:
+ prepared_jobs: A prepared job dictionary, or list of prepared job dictionaries
+
+ Returns:
+ A Batch object containing the submitted job(s)
+ """
+ if isinstance(prepared_jobs, dict):
+ payload = {'jobs': [prepared_jobs]}
+ else:
+ payload = {'jobs': prepared_jobs}
- payload = {'jobs': [job_dict], 'validate_only': validate_only}
response = self.session.post(urljoin(self.url, '/jobs'), json=payload)
try:
response.raise_for_status()
except HTTPError:
raise HyP3Error('Error while submitting job to HyP3')
- return Job.from_dict(response.json()['jobs'][0])
- def submit_autorift_job(self, granule1: str, granule2: str, name: Optional[str] = None) -> Job:
+ batch = Batch()
+ for job in response.json()['jobs']:
+ batch += Job.from_dict(job)
+ return batch
+
+ def submit_autorift_job(self, granule1: str, granule2: str, name: Optional[str] = None) -> Batch:
"""Submit an autoRIFT job
Args:
granule1: The first granule (scene) to use
granule2: The second granule (scene) to use
- name: A name for the job (must be <= 20 characters)
+ name: A name for the job
Returns:
A Batch object containing the autoRIFT job
"""
+ job_dict = self.prepare_autorift_job(granule1, granule2, name=name)
+ return self.submit_prepared_jobs(prepared_jobs=job_dict)
+
+ @classmethod
+ def prepare_autorift_job(cls, granule1: str, granule2: str, name: Optional[str] = None) -> dict:
+ """Submit an autoRIFT job
+
+ Args:
+ granule1: The first granule (scene) to use
+ granule2: The second granule (scene) to use
+ name: A name for the job
+
+ Returns:
+ A dictionary containing the prepared autoRIFT job
+ """
job_dict = {
'job_parameters': {'granules': [granule1, granule2]},
'job_type': 'AUTORIFT',
}
- return self.submit_job_dict(job_dict=job_dict, name=name)
+ if name is not None:
+ job_dict['name'] = name
+ return job_dict
- def submit_rtc_job(self, granule: str, name: Optional[str] = None, **kwargs) -> Job:
+ def submit_rtc_job(self, granule: str, name: Optional[str] = None, **kwargs) -> Batch:
"""Submit an RTC job
Args:
granule: The granule (scene) to use
- name: A name for the job (must be <= 20 characters)
+ name: A name for the job
**kwargs: Extra job parameters specifying custom processing options
Returns:
A Batch object containing the RTC job
"""
+ job_dict = self.prepare_rtc_job(granule, name=name, **kwargs)
+ return self.submit_prepared_jobs(prepared_jobs=job_dict)
+
+ @classmethod
+ def prepare_rtc_job(cls, granule: str, name: Optional[str] = None, **kwargs) -> dict:
+ """Submit an RTC job
+
+ Args:
+ granule: The granule (scene) to use
+ name: A name for the job
+ **kwargs: Extra job parameters specifying custom processing options
+
+ Returns:
+ A dictionary containing the prepared RTC job
+ """
job_dict = {
'job_parameters': {'granules': [granule], **kwargs},
'job_type': 'RTC_GAMMA',
}
- return self.submit_job_dict(job_dict=job_dict, name=name)
+ if name is not None:
+ job_dict['name'] = name
+ return job_dict
- def submit_insar_job(self, granule1: str, granule2: str, name: Optional[str] = None, **kwargs) -> Job:
+ def submit_insar_job(self, granule1: str, granule2: str, name: Optional[str] = None, **kwargs) -> Batch:
"""Submit an InSAR job
Args:
granule1: The first granule (scene) to use
granule2: The second granule (scene) to use
- name: A name for the job (must be <= 20 characters)
+ name: A name for the job
**kwargs: Extra job parameters specifying custom processing options
Returns:
A Batch object containing the InSAR job
"""
+ job_dict = self.prepare_insar_job(granule1, granule2, name=name, **kwargs)
+ return self.submit_prepared_jobs(prepared_jobs=job_dict)
+
+ @classmethod
+ def prepare_insar_job(cls, granule1: str, granule2: str, name: Optional[str] = None, **kwargs) -> dict:
+ """Submit an InSAR job
+
+ Args:
+ granule1: The first granule (scene) to use
+ granule2: The second granule (scene) to use
+ name: A name for the job
+ **kwargs: Extra job parameters specifying custom processing options
+
+ Returns:
+ A dictionary containing the prepared InSAR job
+ """
job_dict = {
'job_parameters': {'granules': [granule1, granule2], **kwargs},
'job_type': 'INSAR_GAMMA',
}
- return self.submit_job_dict(job_dict=job_dict, name=name)
+ if name is not None:
+ job_dict['name'] = name
+ return job_dict
def my_info(self) -> dict:
"""
|
ASFHyP3__hyp3-sdk-71
|
[
{
"changes": {
"added_entities": [
"hyp3_sdk/jobs.py:Batch.__iter__"
],
"added_modules": null,
"edited_entities": [
"hyp3_sdk/jobs.py:Batch.__len__"
],
"edited_modules": [
"hyp3_sdk/jobs.py:Batch"
]
},
"file": "hyp3_sdk/jobs.py"
}
] |
ASFHyP3/hyp3-sdk
|
b8011c957ce5759bd64007c2116d202fdb5a6dae
|
Batch should be iterable
Attempting to iterate over a Batch object currently fails with `TypeError: 'Batch' object is not iterable`.
```
> import hyp3_sdk
> api = hyp3_sdk.HyP3()
> jobs = api.find_jobs(name='refactor')
> sizes = [job['files'][0]['size'] for job in jobs]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Batch' object is not iterable
```
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 620eb3f..38529ae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ and uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- `HyP3.prepare_insar_job`
### Changed
+- HyP3 `Batch` objects are now iterable
- HyP3 submit methods will always return a `Batch` containing the submitted job(s)
- `HyP3.submit_job_dict` has been renamed to `HyP3.submit_prepared_jobs` and can
submit one or more prepared job dictionaries.
diff --git a/hyp3_sdk/jobs.py b/hyp3_sdk/jobs.py
index 9167d02..38054fa 100644
--- a/hyp3_sdk/jobs.py
+++ b/hyp3_sdk/jobs.py
@@ -129,9 +129,6 @@ class Batch:
jobs = []
self.jobs = jobs
- def __len__(self):
- return len(self.jobs)
-
def __add__(self, other: Union[Job, 'Batch']):
if isinstance(other, Batch):
return Batch(self.jobs + other.jobs)
@@ -140,6 +137,12 @@ class Batch:
else:
raise TypeError(f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'")
+ def __iter__(self):
+ return iter(self.jobs)
+
+ def __len__(self):
+ return len(self.jobs)
+
def __repr__(self):
return str([job.to_dict() for job in self.jobs])
|
ASFHyP3__hyp3-sdk-73
|
[
{
"changes": {
"added_entities": [
"hyp3_sdk/hyp3.py:HyP3.get_job_by_id"
],
"added_modules": null,
"edited_entities": [
"hyp3_sdk/hyp3.py:HyP3._get_job_by_id",
"hyp3_sdk/hyp3.py:HyP3._refresh_job"
],
"edited_modules": [
"hyp3_sdk/hyp3.py:HyP3"
]
},
"file": "hyp3_sdk/hyp3.py"
}
] |
ASFHyP3/hyp3-sdk
|
1fec8b5ae4c2cf80392cc6e27a52123e72e320e0
|
_get_job_by_id shouldn't be private
https://github.com/ASFHyP3/hyp3-sdk/blob/develop/hyp3_sdk/hyp3.py#L72
Turns out it's pretty useful generally.
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 71619ef..d83763d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ and uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
submit one or more prepared job dictionaries.
- `Job.download_files` and `Batch.download_files` will (optionally) create the
download location if it doesn't exist
+- `Hyp3._get_job_by_id` has been made public and renamed to `Hyp3.get_job_by_id`
## [0.4.0](https://github.com/ASFHyP3/hyp3-sdk/compare/v0.3.3...v0.4.0)
diff --git a/hyp3_sdk/hyp3.py b/hyp3_sdk/hyp3.py
index 060aca6..6c0c8ef 100644
--- a/hyp3_sdk/hyp3.py
+++ b/hyp3_sdk/hyp3.py
@@ -71,12 +71,20 @@ class HyP3:
warnings.warn('Found zero jobs', UserWarning)
return Batch(jobs)
- def _get_job_by_id(self, job_id):
+ def get_job_by_id(self, job_id: str) -> Job:
+ """Get job by job ID
+
+ Args:
+ job_id: A job ID
+
+ Returns:
+ A Job object
+ """
try:
response = self.session.get(urljoin(self.url, f'/jobs/{job_id}'))
response.raise_for_status()
except RequestException:
- raise HyP3Error('Unable to get job by ID')
+ raise HyP3Error(f'Unable to get job by ID {job_id}')
return Job.from_dict(response.json())
@singledispatchmethod
@@ -150,7 +158,7 @@ class HyP3:
@refresh.register
def _refresh_job(self, job: Job):
- return self._get_job_by_id(job.job_id)
+ return self.get_job_by_id(job.job_id)
def submit_prepared_jobs(self, prepared_jobs: Union[dict, List[dict]]) -> Batch:
"""Submit a prepared job dictionary, or list of prepared job dictionaries
|
ASPP__pelita-412
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "pelita/player/__init__.py"
},
{
"changes": {
"added_entities": null,
"added_modules": [
"pelita/player/base.py:SteppingPlayer"
],
"edited_entities": null,
"edited_modules": [
"pelita/player/base.py:TestPlayer"
]
},
"file": "pelita/player/base.py"
}
] |
ASPP/pelita
|
002ae9e325b1608a324d02749205cd70b4f6da2b
|
pytest warns about our TestPlayer
WC1 /tmp/group1/test/test_drunk_player.py cannot collect test class 'TestPlayer' because it has a __init__ constructor
Maybe rename it?
|
diff --git a/pelita/player/__init__.py b/pelita/player/__init__.py
index cf429bca..bedaae24 100644
--- a/pelita/player/__init__.py
+++ b/pelita/player/__init__.py
@@ -1,7 +1,7 @@
from .base import AbstractTeam, SimpleTeam, AbstractPlayer
-from .base import (StoppingPlayer, TestPlayer, SpeakingPlayer,
+from .base import (StoppingPlayer, SteppingPlayer, SpeakingPlayer,
RoundBasedPlayer, MoveExceptionPlayer, InitialExceptionPlayer,
DebuggablePlayer)
diff --git a/pelita/player/base.py b/pelita/player/base.py
index f07bba65..0e578f2f 100644
--- a/pelita/player/base.py
+++ b/pelita/player/base.py
@@ -516,7 +516,7 @@ class SpeakingPlayer(AbstractPlayer):
self.say("Going %r." % (move,))
return move
-class TestPlayer(AbstractPlayer):
+class SteppingPlayer(AbstractPlayer):
""" A Player with predetermined set of moves.
Parameters
|
ASPP__pelita-619
|
[
{
"changes": {
"added_entities": [
"pelita/layout.py:layout_for_team"
],
"added_modules": [
"pelita/layout.py:layout_for_team"
],
"edited_entities": [
"pelita/layout.py:parse_layout",
"pelita/layout.py:parse_single_layout",
"pelita/layout.py:layout_as_str"
],
"edited_modules": [
"pelita/layout.py:Layout",
"pelita/layout.py:LayoutEncodingException",
"pelita/layout.py:parse_layout",
"pelita/layout.py:parse_single_layout",
"pelita/layout.py:layout_as_str"
]
},
"file": "pelita/layout.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/player/team.py:Bot.__str__",
"pelita/player/team.py:Layout.__init__",
"pelita/player/team.py:Layout.guess_initial_positions",
"pelita/player/team.py:Layout.merge",
"pelita/player/team.py:Layout._repr_html_",
"pelita/player/team.py:Layout.__str__",
"pelita/player/team.py:Layout.__eq__",
"pelita/player/team.py:create_layout",
"pelita/player/team.py:split_layout_str",
"pelita/player/team.py:load_layout"
],
"edited_modules": [
"pelita/player/team.py:Bot",
"pelita/player/team.py:Layout",
"pelita/player/team.py:create_layout",
"pelita/player/team.py:split_layout_str",
"pelita/player/team.py:load_layout"
]
},
"file": "pelita/player/team.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/utils/__init__.py:split_food",
"pelita/utils/__init__.py:setup_test_game"
],
"edited_modules": [
"pelita/utils/__init__.py:split_food",
"pelita/utils/__init__.py:setup_test_game"
]
},
"file": "pelita/utils/__init__.py"
}
] |
ASPP/pelita
|
8c4b83c5fcfd1b748af5cfe8b0b09e93ab5a6406
|
parse_layout should fail when a bot is defined on different coordinates
from pelita.layout import parse_layout
layout = """
######
#000.#
#.111#
###### """
print(parse_layout(layout)['bots'])
[(3, 1), (4, 2), None, None]
should raise `ValueError`
|
diff --git a/pelita/layout.py b/pelita/layout.py
index 1ad10138..6fde0227 100644
--- a/pelita/layout.py
+++ b/pelita/layout.py
@@ -9,12 +9,6 @@ except SyntaxError as err:
print("Invalid syntax in __layouts module. Pelita will not be able to use built-in layouts.")
print(err)
-class Layout:
- pass
-
-class LayoutEncodingException(Exception):
- """ Signifies a problem with the encoding of a layout. """
- pass
def get_random_layout(filter=''):
""" Return a random layout string from the available ones.
@@ -98,7 +92,7 @@ def get_layout_by_name(layout_name):
# thus reraise as ValueError with appropriate error message.
raise ValueError("Layout: '%s' is not known." % ke.args)
-def parse_layout(layout_str):
+def parse_layout(layout_str, allow_enemy_chars=False):
"""Parse a layout string
Return a dict
@@ -130,8 +124,19 @@ def parse_layout(layout_str):
# . 3#
########
- In this case, bot '0' and bot '2' are on top of each other at position (1,1)
- """
+ In this case, bot '0' and bot '2' are on top of each other at position (1,1)
+
+ If `allow_enemy_chars` is True, we additionally allow for the definition of
+ at most 2 enemy characters with the letter "E". The returned dict will then
+ additionally contain an entry "enemy" which contains these coordinates.
+ If only one enemy character is given, both will be assumed sitting on the
+ same spot. """
+
+ if allow_enemy_chars:
+ num_bots = 2
+ else:
+ num_bots = 4
+
layout_list = []
start = False
for i, line in enumerate(layout_str.splitlines()):
@@ -160,24 +165,68 @@ def parse_layout(layout_str):
# the last layout has not been closed, complain here!
raise ValueError(f"Layout does not end with a row of walls (line: {i})!")
- # initialize walls, food and bots from the first layout
- out = parse_single_layout(layout_list.pop(0))
+ # set empty default values
+ walls = []
+ food = []
+ bots = [None] * num_bots
+ if allow_enemy_chars:
+ enemy = []
+
+ # iterate through all layouts
for layout in layout_list:
- items = parse_layout(layout)
+ items = parse_single_layout(layout, num_bots=num_bots, allow_enemy_chars=allow_enemy_chars)
+ # initialize walls from the first layout
+ if not walls:
+ walls = items['walls']
+
# walls should always be the same
- if items['walls'] != out['walls']:
+ if items['walls'] != walls:
raise ValueError('Walls are not equal in all layouts!')
+
# add the food, removing duplicates
- out['food'] = list(set(out['food'] + items['food']))
+ food = list(set(food + items['food']))
+
+ # add the enemy, removing duplicates
+ if allow_enemy_chars:
+ enemy = list(set(enemy + items['enemy']))
+
# add the bots
for bot_idx, bot_pos in enumerate(items['bots']):
if bot_pos:
- # this bot position is not None, overwrite whatever we had before
- out['bots'][bot_idx] = bot_pos
+ # this bot position is not None, overwrite whatever we had before, unless
+ # it already holds a different coordinate
+ if bots[bot_idx] and bots[bot_idx] != bot_pos:
+ raise ValueError(f"Cannot set bot {bot_idx} to position {bot_pos} (already at {bots[bot_idx]}).")
+ bots[bot_idx] = bot_pos
+
+ if allow_enemy_chars:
+ # validate that we have at most two enemies
+ if len(enemy) > 2:
+ raise ValueError(f"More than two enemies defined: {enemy}!")
+ elif len(enemy) == 2:
+ # do nothing
+ pass
+ elif len(enemy) == 1:
+ # we use the position for both enemies
+ enemy = [enemy[0], enemy[0]]
+ else:
+ enemy = [None, None]
+
+ # build parsed layout, ensuring walls and food are sorted
+ out = {
+ 'walls': sorted(walls),
+ 'food': sorted(food),
+ 'bots': bots
+ }
+
+ if allow_enemy_chars:
+ # sort the enemy characters
+ # be careful, since it may contain None
+ out['enemy'] = sorted(enemy, key=lambda x: () if x is None else x)
return out
-def parse_single_layout(layout_str):
+def parse_single_layout(layout_str, num_bots=4, allow_enemy_chars=False):
"""Parse a single layout from a string
See parse_layout for details about valid layout strings.
@@ -228,8 +277,10 @@ def parse_single_layout(layout_str):
height = len(rows)
walls = []
food = []
- # bot positions (we assume 4 bots)
- bots = [None]*4
+ # bot positions
+ bots = [None] * num_bots
+ # enemy positions (only used for team-style layouts)
+ enemy = []
# iterate through the grid of characters
for y, row in enumerate(rows):
@@ -245,22 +296,37 @@ def parse_single_layout(layout_str):
elif char == ' ':
# empty
continue
+ elif char == 'E':
+ # enemy
+ if allow_enemy_chars:
+ enemy.append(coord)
+ else:
+ raise ValueError(f"Enemy character not allowed.")
else:
# bot
try:
- # we expect an 0<=index<=3
+ # we expect an 0<=index<=num_bots
bot_idx = int(char)
if bot_idx >= len(bots):
# reuse the except below
raise ValueError
except ValueError:
raise ValueError(f"Unknown character {char} in maze!")
+
+ # bot_idx is a valid character.
+ if bots[bot_idx]:
+ # bot_idx has already been set before
+ raise ValueError(f"Cannot set bot {bot_idx} to position {coord} (already at {bots[bot_idx]}).")
bots[bot_idx] = coord
walls.sort()
food.sort()
- return {'walls':walls, 'food':food, 'bots':bots}
+ out = {'walls':walls, 'food':food, 'bots':bots}
+ if allow_enemy_chars:
+ enemy.sort()
+ out['enemy'] = enemy
+ return out
-def layout_as_str(*, walls, food=None, bots=None):
+def layout_as_str(*, walls, food=None, bots=None, enemy=None):
"""Given walls, food and bots return a string layout representation
Returns a combined layout string.
@@ -279,21 +345,27 @@ def layout_as_str(*, walls, food=None, bots=None):
width = max(walls)[0] + 1
height = max(walls)[1] + 1
+ # enemy is optional
+ if enemy is None:
+ enemy = []
# flag to check if we have overlapping objects
# when need_combined is True, we force the printing of a combined layout
# string:
# - the first layout will have walls and food
- # - subsequent layouts will have walls and bots
+ # - subsequent layouts will have walls and bots (and enemies, if given)
# You'll get as many layouts as you have overlapping bots
need_combined = False
+ # combine bots an enemy lists
+ bots_and_enemy = bots + enemy if enemy else bots
+
# first, check if we have overlapping bots
- if len(set(bots)) != len(bots):
+ if len(set(bots_and_enemy)) != len(bots_and_enemy):
need_combined = True
else:
- need_combined = any(coord in food for coord in bots)
+ need_combined = any(coord in food for coord in bots_and_enemy)
# then, check that bots are not overlapping with food
out = io.StringIO()
@@ -311,6 +383,8 @@ def layout_as_str(*, walls, food=None, bots=None):
# we won't need a combined layout later
if (x, y) in bots:
out.write(str(bots.index((x, y))))
+ elif (x, y) in enemy:
+ out.write("E")
else:
out.write(' ')
else:
@@ -333,6 +407,14 @@ def layout_as_str(*, walls, food=None, bots=None):
# if still no bot was seen here we have to start with an empty list
coord_bots[pos] = coord_bots.get(pos, []) + [str(idx)]
+ # add enemies to mapping
+ for pos in enemy:
+ if pos is None:
+ # if an enemy coordinate is None
+ # don't put the enemy in the layout
+ continue
+ coord_bots[pos] = coord_bots.get(pos, []) + ["E"]
+
# loop through the bot coordinates
while coord_bots:
for y in range(height):
@@ -358,6 +440,28 @@ def layout_as_str(*, walls, food=None, bots=None):
return out.getvalue()
+def layout_for_team(layout, is_blue=True):
+ """ Converts a layout dict with 4 bots to a layout
+ from the view of the specified team.
+ """
+ if "enemy" in layout:
+ raise ValueError("Layout is already in team-style.")
+
+ if is_blue:
+ bots = layout['bots'][0::2]
+ enemy = layout['bots'][1::2]
+ else:
+ bots = layout['bots'][1::2]
+ enemy = layout['bots'][0::2]
+
+ return {
+ 'walls': layout['walls'][:],
+ 'food': layout['food'][:],
+ 'bots': bots,
+ 'enemy': enemy,
+ }
+
+
def wall_dimensions(walls):
""" Given a list of walls, returns a tuple of (width, height)."""
width = max(walls)[0] + 1
diff --git a/pelita/player/team.py b/pelita/player/team.py
index 58b3efe6..a6a41f58 100644
--- a/pelita/player/team.py
+++ b/pelita/player/team.py
@@ -1,20 +1,20 @@
import collections
-from functools import reduce
-from io import StringIO
import logging
import os
-from pathlib import Path
import random
import subprocess
import traceback
+from functools import reduce
+from io import StringIO
+from pathlib import Path
import zmq
-from .. import libpelita, layout
+from .. import layout, libpelita
from ..exceptions import PlayerDisconnected, PlayerTimeout
-from ..network import ZMQConnection, ZMQClientError, ZMQReplyTimeout, ZMQUnreachablePeer
-
+from ..layout import layout_as_str, parse_layout, wall_dimensions
+from ..network import ZMQClientError, ZMQConnection, ZMQReplyTimeout, ZMQUnreachablePeer
_logger = logging.getLogger(__name__)
@@ -599,10 +599,10 @@ class Bot:
with StringIO() as out:
out.write(header)
- layout = Layout(walls=bot.walls[:],
- food=bot.food + bot.enemy[0].food,
- bots=[b.position for b in bot._team],
- enemy=[e.position for e in bot.enemy])
+ layout = layout_as_str(walls=bot.walls[:],
+ food=bot.food + bot.enemy[0].food,
+ bots=[b.position for b in bot._team],
+ enemy=[e.position for e in bot.enemy])
out.write(str(layout))
return out.getvalue()
@@ -669,214 +669,6 @@ def make_bots(*, walls, team, enemy, round, bot_turn, rng):
return team_bots[bot_turn]
-# @dataclass
-class Layout:
- def __init__(self, walls, food, bots, enemy):
- if not food:
- food = []
-
- if not bots:
- bots = [None, None]
-
- if not enemy:
- enemy = [None, None]
-
- # input validation
- for pos in [*food, *bots, *enemy]:
- if pos:
- if len(pos) != 2:
- raise ValueError("Items must be tuples of length 2.")
- if pos in walls:
- raise ValueError("Item at %r placed on walls." % (pos,))
- else:
- walls_width = max(walls)[0] + 1
- walls_height = max(walls)[1] + 1
- if not (0 <= pos[0] < walls_width) or not (0 <= pos[1] < walls_height):
- raise ValueError("Item at %r not in bounds." % (pos,))
-
-
- if len(bots) > 2:
- raise ValueError("Too many bots given.")
-
- self.walls = sorted(walls)
- self.food = sorted(food)
- self.bots = bots
- self.enemy = enemy
- self.initial_positions = self.guess_initial_positions(self.walls)
-
- def guess_initial_positions(self, walls):
- """ Returns the free positions that are closest to the bottom left and
- top right corner. The algorithm starts searching from (1, -2) and (-2, 1)
- respectively and uses the manhattan distance for judging what is closest.
- On equal distances, a smaller distance in the x value is preferred.
- """
- walls_width = max(walls)[0] + 1
- walls_height = max(walls)[1] + 1
-
- left_start = (1, walls_height - 2)
- left_initials = []
- right_start = (walls_width - 2, 1)
- right_initials = []
-
- dist = 0
- while len(left_initials) < 2:
- # iterate through all possible x distances (inclusive)
- for x_dist in range(dist + 1):
- y_dist = dist - x_dist
- pos = (left_start[0] + x_dist, left_start[1] - y_dist)
- # if both coordinates are out of bounds, we stop
- if not (0 <= pos[0] < walls_width) and not (0 <= pos[1] < walls_height):
- raise ValueError("Not enough free initial positions.")
- # if one coordinate is out of bounds, we just continue
- if not (0 <= pos[0] < walls_width) or not (0 <= pos[1] < walls_height):
- continue
- # check if the new value is free
- if not pos in walls:
- left_initials.append(pos)
-
- if len(left_initials) == 2:
- break
-
- dist += 1
-
- dist = 0
- while len(right_initials) < 2:
- # iterate through all possible x distances (inclusive)
- for x_dist in range(dist + 1):
- y_dist = dist - x_dist
- pos = (right_start[0] - x_dist, right_start[1] + y_dist)
- # if both coordinates are out of bounds, we stop
- if not (0 <= pos[0] < walls_width) and not (0 <= pos[1] < walls_height):
- raise ValueError("Not enough free initial positions.")
- # if one coordinate is out of bounds, we just continue
- if not (0 <= pos[0] < walls_width) or not (0 <= pos[1] < walls_height):
- continue
- # check if the new value is free
- if not pos in walls:
- right_initials.append(pos)
-
- if len(right_initials) == 2:
- break
-
- dist += 1
-
- # lower indices start further away
- left_initials.reverse()
- right_initials.reverse()
- return left_initials, right_initials
-
- def merge(self, other):
- """ Merges `self` with the `other` layout.
- """
-
- if not self.walls:
- self.walls = other.walls
- if self.walls != other.walls:
- raise ValueError("Walls are not equal.")
-
- self.food += other.food
- # remove duplicates
- self.food = list(set(self.food))
-
- # update all newer bot positions
- for idx, b in enumerate(other.bots):
- if b:
- self.bots[idx] = b
-
- # merge all enemies and then take the last 2
- enemies = [e for e in [*self.enemy, *other.enemy] if e is not None]
- self.enemy = enemies[-2:]
- # if self.enemy smaller than 2, we pad with None again
- for _ in range(2 - len(self.enemy)):
- self.enemy.append(None)
-
- # return our merged self
- return self
-
- def _repr_html_(self):
- walls = self.walls
- walls_width = max(walls)[0] + 1
- walls_height = max(walls)[1] + 1
- with StringIO() as out:
- out.write("<table>")
- for y in range(walls_height):
- out.write("<tr>")
- for x in range(walls_width):
- if (x, y) in walls:
- bg = 'style="background-color: {}"'.format(
- "rgb(94, 158, 217)" if x < walls_width // 2 else
- "rgb(235, 90, 90)")
- elif (x, y) in self.initial_positions[0]:
- bg = 'style="background-color: #ffffcc"'
- elif (x, y) in self.initial_positions[1]:
- bg = 'style="background-color: #ffffcc"'
- else:
- bg = ""
- out.write("<td %s>" % bg)
- if (x, y) in walls: out.write("#")
- if (x, y) in self.food: out.write('<span style="color: rgb(247, 150, 213)">●</span>')
- for idx, pos in enumerate(self.bots):
- if pos == (x, y):
- out.write(str(idx))
- for pos in self.enemy:
- if pos == (x, y):
- out.write('E')
- out.write("</td>")
- out.write("</tr>")
- out.write("</table>")
- return out.getvalue()
-
- def __str__(self):
- walls = self.walls
- walls_width = max(walls)[0] + 1
- walls_height = max(walls)[1] + 1
- with StringIO() as out:
- out.write('\n')
- # first, print walls and food
- for y in range(walls_height):
- for x in range(walls_width):
- if (x, y) in walls: out.write('#')
- elif (x, y) in self.food: out.write('.')
- else: out.write(' ')
- out.write('\n')
- out.write('\n')
- # print walls and bots
-
- # Do we have bots/enemies sitting on each other?
-
- # assign bots to their positions
- bots = {}
- for pos in self.enemy:
- bots[pos] = bots.get(pos, []) + ['E']
- for idx, pos in enumerate(self.bots):
- bots[pos] = bots.get(pos, []) + [str(idx)]
- # strip all None positions from bots
- try:
- bots.pop(None)
- except KeyError:
- pass
-
- while bots:
- for y in range(walls_height):
- for x in range(walls_width):
- if (x, y) in walls: out.write('#')
- elif (x, y) in bots:
- elem = bots[(x, y)].pop(0)
- out.write(elem)
- # cleanup
- if len(bots[(x, y)]) == 0:
- bots.pop((x, y))
-
- else: out.write(' ')
- out.write('\n')
- out.write('\n')
- return out.getvalue()
-
- def __eq__(self, other):
- return ((self.walls, self.food, self.bots, self.enemy, self.initial_positions) ==
- (other.walls, other.food, other.bots, self.enemy, other.initial_positions))
-
-
def create_layout(*layout_strings, food=None, bots=None, enemy=None):
""" Create a layout from layout strings with additional food, bots and enemy positions.
@@ -887,106 +679,42 @@ def create_layout(*layout_strings, food=None, bots=None, enemy=None):
======
ValueError
If walls are not equal in all layouts
+ If enemy argument is not a list of two
"""
- # layout_strings can be a list of strings or one huge string
- # with many layouts after another
- layouts = [
- load_layout(layout)
- for layout_str in layout_strings
- for layout in split_layout_str(layout_str)
- ]
- merged = reduce(lambda x, y: x.merge(y), layouts)
- additional_layout = Layout(walls=merged.walls, food=food, bots=bots, enemy=enemy)
- merged.merge(additional_layout)
- return merged
-
-def split_layout_str(layout_str):
- """ Turns a layout string containing many layouts into a list
- of simple layouts.
- """
- out = []
- current_layout = []
- for row in layout_str.splitlines():
- stripped = row.strip()
- if not stripped:
- # found an empty line
- # if we have a current_layout, append it to out
- # and reset it
- if current_layout:
- out.append(current_layout)
- current_layout = []
- continue
- # non-empty line: append to current_layout
- current_layout.append(row)
-
- # We still have a current layout at the end: append
- if current_layout:
- out.append(current_layout)
-
- return ['\n'.join(l) for l in out]
-
-def load_layout(layout_str):
- """ Loads a *single* (partial) layout from a string. """
- build = []
- width = None
- height = None
-
- food = []
- bots = [None, None]
- enemy = []
-
- for row in layout_str.splitlines():
- stripped = row.strip()
- if not stripped:
- continue
- if width is not None:
- if len(stripped) != width:
- raise ValueError("Layout has differing widths.")
- width = len(stripped)
- build.append(stripped)
-
- height = len(build)
- data=list("".join(build))
- def idx_to_coord(idx):
- """ Maps a 1-D index to a 2-D coord given a width and height. """
- return (idx % width, idx // width)
-
- # Check that the layout is surrounded with walls
- for idx, char in enumerate(data):
- x, y = idx_to_coord(idx)
- if x == 0 or x == width - 1:
- if not char == '#':
- raise ValueError(f"Layout not surrounded with # at ({x}, {y}).")
- if y == 0 or y == height - 1:
- if not char == '#':
- raise ValueError(f"Layout not surrounded with # at ({x}, {y}).")
-
- walls = []
- # extract the non-wall values from mesh
- for idx, char in enumerate(data):
- coord = idx_to_coord(idx)
- # We know that each char is only one character, so it is
- # either wall or something else
- if '#' in char:
- walls.append(coord)
- # free: skip
- elif ' ' in char:
- continue
- # food
- elif '.' in char:
- food.append(coord)
- # other
- else:
- if 'E' in char:
- # We can have several undefined enemies
- enemy.append(coord)
- elif '0' in char:
- bots[0] = coord
- elif '1' in char:
- bots[1] = coord
- else:
- raise ValueError("Unknown character %s in maze." % char)
+ layout_str = "\n\n".join(layout_strings)
+ parsed_layout = parse_layout(layout_str, allow_enemy_chars=True)
+
+ width, height = wall_dimensions(parsed_layout['walls'])
- walls = sorted(walls)
- return Layout(walls, food, bots, enemy)
+ def _check_valid_pos(pos, item):
+ if pos in parsed_layout['walls']:
+ raise ValueError(f"{item} must not be on wall (given: {pos})!")
+ if not ((0 <= pos[0] < width) and (0 <= pos[1] < height)):
+ raise ValueError(f"{item} is outside of maze (given: {pos} but dimensions are {width}x{height})!")
+
+ # if additional food was supplied, we add it
+ if food:
+ for f in food:
+ _check_valid_pos(f, "food")
+ parsed_layout['food'] = sorted(list(set(food + parsed_layout['food'])))
+
+ # override bots if given and not None
+ if bots is not None:
+ if len(bots) > 2:
+ raise ValueError(f"bots must not be more than 2 ({bots})!")
+ for idx, pos in enumerate(bots):
+ if pos is not None:
+ _check_valid_pos(pos, "bot")
+ parsed_layout['bots'][idx] = pos
+
+ # override enemies if given
+ if enemy is not None:
+ if not len(enemy) == 2:
+ raise ValueError(f"enemy must be a list of 2 ({enemy})!")
+ for idx, e in enumerate(enemy):
+ if e is not None:
+ _check_valid_pos(e, "enemy")
+ parsed_layout['enemy'][idx] = e
+
+ return parsed_layout
diff --git a/pelita/utils/__init__.py b/pelita/utils/__init__.py
index 4d63bbe4..c2172229 100644
--- a/pelita/utils/__init__.py
+++ b/pelita/utils/__init__.py
@@ -3,11 +3,10 @@ import random
from ..player.team import create_layout, make_bots
from ..graph import Graph
-def split_food(layout):
- width = max(layout.walls)[0] + 1
+def split_food(width, food):
team_food = [set(), set()]
- for pos in layout.food:
+ for pos in food:
idx = pos[0] // (width // 2)
team_food[idx].add(pos)
return team_food
@@ -26,7 +25,9 @@ def setup_test_game(*, layout, game=None, is_blue=True, round=None, score=None,
score = [0, 0]
layout = create_layout(layout, food=food, bots=bots, enemy=enemy)
- food = split_food(layout)
+ width = max(layout['walls'])[0] + 1
+
+ food = split_food(width, layout['food'])
if is_blue:
team_index = 0
@@ -38,7 +39,7 @@ def setup_test_game(*, layout, game=None, is_blue=True, round=None, score=None,
rng = random.Random(seed)
team = {
- 'bot_positions': layout.bots[:],
+ 'bot_positions': layout['bots'][:],
'team_index': team_index,
'score': score[team_index],
'kills': [0]*2,
@@ -49,7 +50,7 @@ def setup_test_game(*, layout, game=None, is_blue=True, round=None, score=None,
'name': "blue" if is_blue else "red"
}
enemy = {
- 'bot_positions': layout.enemy[:],
+ 'bot_positions': layout['enemy'][:],
'team_index': enemy_index,
'score': score[enemy_index],
'kills': [0]*2,
@@ -57,11 +58,11 @@ def setup_test_game(*, layout, game=None, is_blue=True, round=None, score=None,
'bot_eaten': [False]*2,
'error_count': 0,
'food': food[enemy_index],
- 'is_noisy': [False] * len(layout.enemy),
+ 'is_noisy': [False] * len(layout['enemy']),
'name': "red" if is_blue else "blue"
}
- bot = make_bots(walls=layout.walls[:],
+ bot = make_bots(walls=layout['walls'][:],
team=team,
enemy=enemy,
round=round,
|
ASPP__pelita-635
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/game.py:setup_game",
"pelita/game.py:prepare_bot_state",
"pelita/game.py:apply_move"
],
"edited_modules": [
"pelita/game.py:setup_game",
"pelita/game.py:prepare_bot_state",
"pelita/game.py:apply_move"
]
},
"file": "pelita/game.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/player/team.py:Team.get_move",
"pelita/player/team.py:Bot.__init__",
"pelita/player/team.py:make_bots"
],
"edited_modules": [
"pelita/player/team.py:Team",
"pelita/player/team.py:Bot",
"pelita/player/team.py:make_bots"
]
},
"file": "pelita/player/team.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/utils.py:setup_test_game"
],
"edited_modules": [
"pelita/utils.py:setup_test_game"
]
},
"file": "pelita/utils.py"
}
] |
ASPP/pelita
|
ffe76f4adeca90e7c9e4542ab61a1deb5081408f
|
rename Bot.has_respawned
What about renaming `Bot.has_respawned` to `Bot.was_killed`? The word _respawned_ is totally meaningless for most non-hardcore programmers.
|
diff --git a/pelita/game.py b/pelita/game.py
index 5789a9b3..2dd68761 100644
--- a/pelita/game.py
+++ b/pelita/game.py
@@ -275,7 +275,7 @@ def setup_game(team_specs, *, layout_dict, max_rounds=300, layout_name="", seed=
kills = [0]*4,
# List of boolean flags weather bot has been eaten since its last move
- bot_eaten = [False]*4,
+ bot_was_killed = [False]*4,
#: Messages the bots say. Keeps only the recent one at the respective bot’s index.
say=[""] * 4,
@@ -418,7 +418,7 @@ def prepare_bot_state(game_state, idx=None):
'score': game_state['score'][own_team],
'kills': game_state['kills'][own_team::2],
'deaths': game_state['deaths'][own_team::2],
- 'bot_eaten': game_state['bot_eaten'][own_team::2],
+ 'bot_was_killed': game_state['bot_was_killed'][own_team::2],
'error_count': len(game_state['errors'][own_team]),
'food': list(game_state['food'][own_team]),
'name': game_state['team_names'][own_team]
@@ -431,7 +431,7 @@ def prepare_bot_state(game_state, idx=None):
'score': game_state['score'][enemy_team],
'kills': game_state['kills'][enemy_team::2],
'deaths': game_state['deaths'][enemy_team::2],
- 'bot_eaten': game_state['bot_eaten'][enemy_team::2],
+ 'bot_was_killed': game_state['bot_was_killed'][enemy_team::2],
'error_count': 0, # TODO. Could be left out for the enemy
'food': list(game_state['food'][enemy_team]),
'name': game_state['team_names'][enemy_team]
@@ -627,14 +627,14 @@ def apply_move(gamestate, bot_position):
n_round = gamestate["round"]
kills = gamestate["kills"]
deaths = gamestate["deaths"]
- bot_eaten = gamestate["bot_eaten"]
+ bot_was_killed = gamestate["bot_was_killed"]
fatal_error = True if gamestate["fatal_errors"][team] else False
#TODO how are fatal errors passed to us? dict with same structure as regular errors?
#TODO do we need to communicate that fatal error was the reason for game over in any other way?
- # reset our own bot_eaten flag
- bot_eaten[turn] = False
+ # reset our own bot_was_killed flag
+ bot_was_killed[turn] = False
# previous errors
team_errors = gamestate["errors"][team]
@@ -694,7 +694,7 @@ def apply_move(gamestate, bot_position):
bots[enemy_idx] = init_positions[enemy_idx]
kills[turn] += 1
deaths[enemy_idx] += 1
- bot_eaten[enemy_idx] = True
+ bot_was_killed[enemy_idx] = True
_logger.info(f"Bot {enemy_idx} reappears at {bots[enemy_idx]}.")
else:
# check if we have been eaten
@@ -706,7 +706,7 @@ def apply_move(gamestate, bot_position):
bots[turn] = init_positions[turn]
deaths[turn] += 1
kills[enemies_on_target[0]] += 1
- bot_eaten[turn] = True
+ bot_was_killed[turn] = True
_logger.info(f"Bot {turn} reappears at {bots[turn]}.")
errors = gamestate["errors"]
@@ -717,7 +717,7 @@ def apply_move(gamestate, bot_position):
"score": score,
"deaths": deaths,
"kills": kills,
- "bot_eaten": bot_eaten,
+ "bot_was_killed": bot_was_killed,
"errors": errors,
}
diff --git a/pelita/player/team.py b/pelita/player/team.py
index 5e80eaa5..a98d6140 100644
--- a/pelita/player/team.py
+++ b/pelita/player/team.py
@@ -104,8 +104,8 @@ class Team:
team = me._team
for idx, mybot in enumerate(team):
- # If a bot has been eaten, we reset it’s bot track
- if mybot.eaten:
+ # If a bot has been killed, we reset it’s bot track
+ if mybot.was_killed:
self._bot_track[idx] = []
# Add our track
@@ -414,7 +414,7 @@ class Bot:
score,
kills,
deaths,
- eaten,
+ was_killed,
random,
round,
is_blue,
@@ -441,7 +441,7 @@ class Bot:
self.score = score
self.kills = kills
self.deaths = deaths
- self.eaten = eaten
+ self.was_killed = was_killed
self._bot_index = bot_index
self.round = round
self.is_blue = is_blue
@@ -636,7 +636,7 @@ def make_bots(*, walls, team, enemy, round, bot_turn, rng):
score=team['score'],
deaths=team['deaths'][idx],
kills=team['kills'][idx],
- eaten=team['bot_eaten'][idx],
+ was_killed=team['bot_was_killed'][idx],
error_count=team['error_count'],
food=team['food'],
walls=walls,
@@ -658,7 +658,7 @@ def make_bots(*, walls, team, enemy, round, bot_turn, rng):
score=enemy['score'],
kills=enemy['kills'][idx],
deaths=enemy['deaths'][idx],
- eaten=enemy['bot_eaten'][idx],
+ was_killed=enemy['bot_was_killed'][idx],
is_noisy=enemy['is_noisy'][idx],
error_count=enemy['error_count'],
food=enemy['food'],
diff --git a/pelita/utils.py b/pelita/utils.py
index 2ba81335..4da42bb9 100644
--- a/pelita/utils.py
+++ b/pelita/utils.py
@@ -58,7 +58,7 @@ def setup_test_game(*, layout, game=None, is_blue=True, round=None, score=None,
'score': score[team_index],
'kills': [0]*2,
'deaths': [0]*2,
- 'bot_eaten' : [False]*2,
+ 'bot_was_killed' : [False]*2,
'error_count': 0,
'food': food[team_index],
'name': "blue" if is_blue else "red"
@@ -69,7 +69,7 @@ def setup_test_game(*, layout, game=None, is_blue=True, round=None, score=None,
'score': score[enemy_index],
'kills': [0]*2,
'deaths': [0]*2,
- 'bot_eaten': [False]*2,
+ 'bot_was_killed': [False]*2,
'error_count': 0,
'food': food[enemy_index],
'is_noisy': [False] * len(layout['enemy']),
|
ASPP__pelita-655
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/layout.py:parse_layout",
"pelita/layout.py:parse_single_layout",
"pelita/layout.py:layout_as_str"
],
"edited_modules": [
"pelita/layout.py:parse_layout",
"pelita/layout.py:parse_single_layout",
"pelita/layout.py:layout_as_str"
]
},
"file": "pelita/layout.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/player/team.py:Bot.__str__",
"pelita/player/team.py:create_layout"
],
"edited_modules": [
"pelita/player/team.py:Bot",
"pelita/player/team.py:create_layout"
]
},
"file": "pelita/player/team.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/utils.py:setup_test_game"
],
"edited_modules": [
"pelita/utils.py:setup_test_game"
]
},
"file": "pelita/utils.py"
}
] |
ASPP/pelita
|
1108fc71cdc9a7eeb4563149e9821255d6f56bf3
|
print(bot) should show which enemies are noisy
This will hopefully avoid confusion.
One remark: since we got rid of set_initial in the new-style API, the teams never see their enemies sitting unnoised on their initial positions, which has been a nice (and easy) starting point for filtering. Question: Do we want to be explicit about how the initial positions are fixed (ie. add an example) or do we want them to figure it out themselves?
|
diff --git a/pelita/layout.py b/pelita/layout.py
index 369da014..df604a43 100644
--- a/pelita/layout.py
+++ b/pelita/layout.py
@@ -117,8 +117,9 @@ def parse_layout(layout_str, allow_enemy_chars=False):
In this case, bot '0' and bot '2' are on top of each other at position (1,1)
If `allow_enemy_chars` is True, we additionally allow for the definition of
- at most 2 enemy characters with the letter "E". The returned dict will then
- additionally contain an entry "enemy" which contains these coordinates.
+ at most 2 enemy characters with the letters "E" and "?". The returned dict will
+ then additionally contain an entry "enemy" which contains these coordinates and
+ an entry "is_noisy" that specifies which of the given enemies is noisy.
If only one enemy character is given, both will be assumed sitting on the
same spot. """
@@ -161,6 +162,7 @@ def parse_layout(layout_str, allow_enemy_chars=False):
bots = [None] * num_bots
if allow_enemy_chars:
enemy = []
+ noisy_enemy = set()
# iterate through all layouts
for layout in layout_list:
@@ -178,7 +180,10 @@ def parse_layout(layout_str, allow_enemy_chars=False):
# add the enemy, removing duplicates
if allow_enemy_chars:
- enemy = list(set(enemy + items['enemy']))
+ # enemy contains _all_ enemies
+ enemy = list(set(enemy + items['enemy'] + items['noisy_enemy']))
+ # noisy_enemy contains only the noisy enemies
+ noisy_enemy.update(items['noisy_enemy'])
# add the bots
for bot_idx, bot_pos in enumerate(items['bots']):
@@ -213,6 +218,7 @@ def parse_layout(layout_str, allow_enemy_chars=False):
# sort the enemy characters
# be careful, since it may contain None
out['enemy'] = sorted(enemy, key=lambda x: () if x is None else x)
+ out['is_noisy'] = [e in noisy_enemy for e in out['enemy']]
return out
@@ -271,6 +277,7 @@ def parse_single_layout(layout_str, num_bots=4, allow_enemy_chars=False):
bots = [None] * num_bots
# enemy positions (only used for team-style layouts)
enemy = []
+ noisy_enemy = []
# iterate through the grid of characters
for y, row in enumerate(rows):
@@ -292,6 +299,12 @@ def parse_single_layout(layout_str, num_bots=4, allow_enemy_chars=False):
enemy.append(coord)
else:
raise ValueError(f"Enemy character not allowed.")
+ elif char == '?':
+ # noisy_enemy
+ if allow_enemy_chars:
+ noisy_enemy.append(coord)
+ else:
+ raise ValueError(f"Enemy character not allowed.")
else:
# bot
try:
@@ -312,11 +325,11 @@ def parse_single_layout(layout_str, num_bots=4, allow_enemy_chars=False):
food.sort()
out = {'walls':walls, 'food':food, 'bots':bots}
if allow_enemy_chars:
- enemy.sort()
- out['enemy'] = enemy
+ out['enemy'] = sorted(enemy)
+ out['noisy_enemy'] = sorted(noisy_enemy)
return out
-def layout_as_str(*, walls, food=None, bots=None, enemy=None):
+def layout_as_str(*, walls, food=None, bots=None, enemy=None, is_noisy=None):
"""Given walls, food and bots return a string layout representation
Returns a combined layout string.
@@ -339,6 +352,15 @@ def layout_as_str(*, walls, food=None, bots=None, enemy=None):
if enemy is None:
enemy = []
+ # if noisy is given, it must be of the same length as enemy
+ if is_noisy is None:
+ noisy_enemies = set()
+ elif len(is_noisy) != len(enemy):
+ raise ValueError("Parameter `noisy` must have same length as `enemy`.")
+ else:
+ # if an enemy is flagged as noisy, we put it into the set of noisy_enemies
+ noisy_enemies = {e for e, e_is_noisy in zip(enemy, is_noisy) if e_is_noisy}
+
# flag to check if we have overlapping objects
# when need_combined is True, we force the printing of a combined layout
@@ -374,7 +396,10 @@ def layout_as_str(*, walls, food=None, bots=None, enemy=None):
if (x, y) in bots:
out.write(str(bots.index((x, y))))
elif (x, y) in enemy:
- out.write("E")
+ if (x, y) in noisy_enemies:
+ out.write("?")
+ else:
+ out.write("E")
else:
out.write(' ')
else:
@@ -403,7 +428,8 @@ def layout_as_str(*, walls, food=None, bots=None, enemy=None):
# if an enemy coordinate is None
# don't put the enemy in the layout
continue
- coord_bots[pos] = coord_bots.get(pos, []) + ["E"]
+ enemy_char = '?' if pos in noisy_enemies else 'E'
+ coord_bots[pos] = coord_bots.get(pos, []) + [enemy_char]
# loop through the bot coordinates
while coord_bots:
diff --git a/pelita/player/team.py b/pelita/player/team.py
index b936994f..5f8f638e 100644
--- a/pelita/player/team.py
+++ b/pelita/player/team.py
@@ -594,7 +594,7 @@ class Bot:
header = ("{blue}{you_blue} vs {red}{you_red}.\n" +
"Playing on {col} side. Current turn: {turn}. Round: {round}, score: {blue_score}:{red_score}. " +
- "timeouts: {blue_timeouts}:{red_timeouts}").format(
+ "timeouts: {blue_timeouts}:{red_timeouts}\n").format(
blue=blue.team_name,
red=red.team_name,
turn=bot.turn,
@@ -614,7 +614,8 @@ class Bot:
layout = layout_as_str(walls=bot.walls[:],
food=bot.food + bot.enemy[0].food,
bots=[b.position for b in bot._team],
- enemy=[e.position for e in bot.enemy])
+ enemy=[e.position for e in bot.enemy],
+ is_noisy=[e.is_noisy for e in bot.enemy])
out.write(str(layout))
return out.getvalue()
@@ -681,7 +682,7 @@ def make_bots(*, walls, team, enemy, round, bot_turn, rng):
return team_bots[bot_turn]
-def create_layout(*layout_strings, food=None, bots=None, enemy=None):
+def create_layout(*layout_strings, food=None, bots=None, enemy=None, is_noisy=None):
""" Create a layout from layout strings with additional food, bots and enemy positions.
Walls must be equal in all layout strings. Food positions will be collected.
@@ -729,4 +730,12 @@ def create_layout(*layout_strings, food=None, bots=None, enemy=None):
_check_valid_pos(e, "enemy")
parsed_layout['enemy'][idx] = e
+ # override is_noisy if given
+ if is_noisy is not None:
+ if not len(is_noisy) == 2:
+ raise ValueError(f"is_noisy must be a list of 2 ({is_noisy})!")
+ for idx, e_is_noisy in enumerate(is_noisy):
+ if e_is_noisy is not None:
+ parsed_layout['is_noisy'][idx] = e_is_noisy
+
return parsed_layout
diff --git a/pelita/utils.py b/pelita/utils.py
index 813e74c1..b238f1ec 100644
--- a/pelita/utils.py
+++ b/pelita/utils.py
@@ -34,7 +34,7 @@ def load_builtin_layout(layout_name, *, is_blue=True):
def setup_test_game(*, layout, game=None, is_blue=True, round=None, score=None, seed=None,
- food=None, bots=None, enemy=None):
+ food=None, bots=None, enemy=None, is_noisy=None):
"""Returns the first bot object given a layout.
The returned Bot instance can be passed to a move function to test its return value.
@@ -45,7 +45,7 @@ def setup_test_game(*, layout, game=None, is_blue=True, round=None, score=None,
if score is None:
score = [0, 0]
- layout = create_layout(layout, food=food, bots=bots, enemy=enemy)
+ layout = create_layout(layout, food=food, bots=bots, enemy=enemy, is_noisy=is_noisy)
width = max(layout['walls'])[0] + 1
food = split_food(width, layout['food'])
@@ -79,7 +79,7 @@ def setup_test_game(*, layout, game=None, is_blue=True, round=None, score=None,
'bot_was_killed': [False]*2,
'error_count': 0,
'food': food[enemy_index],
- 'is_noisy': [False] * len(layout['enemy']),
+ 'is_noisy': layout['is_noisy'],
'name': "red" if is_blue else "blue"
}
|
ASPP__pelita-696
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/layout.py:layout_agnostic"
],
"edited_modules": [
"pelita/layout.py:layout_agnostic"
]
},
"file": "pelita/layout.py"
}
] |
ASPP/pelita
|
557c3a757a24e0f1abe25f7edf5c4ffee83a077e
|
layout_agnostic needs tests and fixes
Currently broken. https://github.com/ASPP/pelita/blob/2f17db5355b4dffae8a130ede549ab869b2f1ce2/pelita/layout.py#L548-L566
|
diff --git a/pelita/layout.py b/pelita/layout.py
index e5797adc..66fa2ebd 100644
--- a/pelita/layout.py
+++ b/pelita/layout.py
@@ -545,9 +545,9 @@ def layout_for_team(layout, is_blue=True, is_noisy=(False, False)):
'is_noisy' : is_noisy,
}
-def layout_agnostic(layout_for_team, is_blue=True):
- """ Converts a layout dict with 2 bots and enemies to a layout
- with 4 bots.
+def layout_agnostic(layout, is_blue=True):
+ """ Converts a layout dict with 2 bots and enemies (team-style)
+ to a layout with 4 bots (server-style).
"""
if "enemy" not in layout:
raise ValueError("Layout is already in server-style.")
|
ASPP__pelita-708
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"check_layout_consistency.py:get_hw",
"check_layout_consistency.py:layout_to_graph"
],
"edited_modules": [
"check_layout_consistency.py:get_hw",
"check_layout_consistency.py:layout_to_graph"
]
},
"file": "check_layout_consistency.py"
},
{
"changes": {
"added_entities": [
"demo/benchmark_game.py:parse_args"
],
"added_modules": [
"demo/benchmark_game.py:parse_args"
],
"edited_entities": [
"demo/benchmark_game.py:run"
],
"edited_modules": [
"demo/benchmark_game.py:run"
]
},
"file": "demo/benchmark_game.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/game.py:setup_game",
"pelita/game.py:prepare_bot_state",
"pelita/game.py:apply_move"
],
"edited_modules": [
"pelita/game.py:setup_game",
"pelita/game.py:prepare_bot_state",
"pelita/game.py:apply_move"
]
},
"file": "pelita/game.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/gamestate_filters.py:noiser",
"pelita/gamestate_filters.py:alter_pos"
],
"edited_modules": [
"pelita/gamestate_filters.py:noiser",
"pelita/gamestate_filters.py:alter_pos"
]
},
"file": "pelita/gamestate_filters.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/layout.py:parse_layout",
"pelita/layout.py:layout_as_str",
"pelita/layout.py:wall_dimensions",
"pelita/layout.py:initial_positions",
"pelita/layout.py:get_legal_positions"
],
"edited_modules": [
"pelita/layout.py:parse_layout",
"pelita/layout.py:layout_as_str",
"pelita/layout.py:wall_dimensions",
"pelita/layout.py:initial_positions",
"pelita/layout.py:get_legal_positions"
]
},
"file": "pelita/layout.py"
},
{
"changes": {
"added_entities": [
"pelita/network.py:SetEncoder.default"
],
"added_modules": [
"pelita/network.py:SetEncoder"
],
"edited_entities": [
"pelita/network.py:ZMQConnection.send",
"pelita/network.py:ZMQPublisher._send"
],
"edited_modules": [
"pelita/network.py:ZMQConnection",
"pelita/network.py:ZMQPublisher"
]
},
"file": "pelita/network.py"
},
{
"changes": {
"added_entities": [
"pelita/player/team.py:_ensure_list_tuples",
"pelita/player/team.py:_ensure_set_tuples"
],
"added_modules": [
"pelita/player/team.py:_ensure_list_tuples",
"pelita/player/team.py:_ensure_set_tuples"
],
"edited_entities": [
"pelita/player/team.py:create_homezones",
"pelita/player/team.py:Team.set_initial",
"pelita/player/team.py:Team.get_move",
"pelita/player/team.py:_ensure_tuples",
"pelita/player/team.py:Bot.__init__",
"pelita/player/team.py:Bot._repr_html_",
"pelita/player/team.py:Bot.__str__",
"pelita/player/team.py:make_bots"
],
"edited_modules": [
"pelita/player/team.py:create_homezones",
"pelita/player/team.py:Team",
"pelita/player/team.py:_ensure_tuples",
"pelita/player/team.py:Bot",
"pelita/player/team.py:make_bots"
]
},
"file": "pelita/player/team.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/ui/tk_canvas.py:_ensure_tuples",
"pelita/ui/tk_canvas.py:TkApplication.init_mesh",
"pelita/ui/tk_canvas.py:TkApplication.draw_universe",
"pelita/ui/tk_canvas.py:TkApplication.draw_selected",
"pelita/ui/tk_canvas.py:TkApplication.observe"
],
"edited_modules": [
"pelita/ui/tk_canvas.py:_ensure_tuples",
"pelita/ui/tk_canvas.py:TkApplication"
]
},
"file": "pelita/ui/tk_canvas.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/utils.py:walls_to_graph",
"pelita/utils.py:setup_test_game"
],
"edited_modules": [
"pelita/utils.py:walls_to_graph",
"pelita/utils.py:setup_test_game"
]
},
"file": "pelita/utils.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/viewer.py:ReplyToViewer._send",
"pelita/viewer.py:ReplayWriter._send"
],
"edited_modules": [
"pelita/viewer.py:ReplyToViewer",
"pelita/viewer.py:ReplayWriter"
]
},
"file": "pelita/viewer.py"
}
] |
ASPP/pelita
|
8c47e30cdf8b6dabf173ebfe71170e36b2aaa35e
|
Add width and height to the layout dictionary
As it is needed in several places, it makes sense to just stick two additional keys into the layout dictionary. Fixing this bug also means getting rid of all `max(walls)[0]+1`, `max(walls)[1]+1`, `sorted(walls)[-1][0]`, `sorted(walls)[-1][1]` spread in the pelita and pelita_template code.
|
diff --git a/check_layout_consistency.py b/check_layout_consistency.py
index f3e873c6..cb6b9689 100644
--- a/check_layout_consistency.py
+++ b/check_layout_consistency.py
@@ -1,36 +1,11 @@
"""Detect if a layout contains "chambers" with food"""
import sys
-import networkx
+import networkx as nx
from pelita.layout import parse_layout
+from pelita.utils import walls_to_graph
-def get_hw(layout):
- walls = layout['walls']
- width = max([coord[0] for coord in walls]) + 1
- height = max([coord[1] for coord in walls]) + 1
- return height, width
-
-def layout_to_graph(layout):
- """Return a networkx.Graph object given the layout
- """
- graph = networkx.Graph()
- height, width = get_hw(layout)
- walls = layout['walls']
- for x in range(width):
- for y in range(height):
- if (x, y) not in walls:
- # this is a free position, get its neighbors
- for delta_x, delta_y in ((1,0), (-1,0), (0,1), (0,-1)):
- neighbor = (x + delta_x, y + delta_y)
- # we don't need to check for getting neighbors out of the maze
- # because our mazes are all surrounded by walls, i.e. our
- # deltas will not put us out of the maze
- if neighbor not in walls:
- # this is a genuine neighbor, add an edge in the graph
- graph.add_edge((x, y), neighbor)
- return graph
-
if __name__ == '__main__':
# either read a file or read from stdin
@@ -44,8 +19,8 @@ if __name__ == '__main__':
# first of all, check for symmetry
# if something is found on the left, it should be found center-mirrored on the right
- height, width = get_hw(layout)
- known = layout['walls']+layout['food']
+ width, height = layout['shape']
+ known = layout['walls'] | set(layout['food'])
layout['empty'] = [(x,y) for x in range(width) for y in range(height) if (x,y) not in known]
for x in range(width // 2):
for y in range(height):
@@ -56,14 +31,14 @@ if __name__ == '__main__':
print(f'{flname}: Layout is not symmetric {coord} != {cmirror}')
- graph = layout_to_graph(layout)
+ graph = walls_to_graph(layout['walls'])
# check for dead_ends
for node, degree in graph.degree():
if degree < 2:
print(f'{flname}: found dead end in {node}')
- if networkx.node_connectivity(graph) < 2:
- entrance = networkx.minimum_node_cut(graph).pop()
+ if nx.node_connectivity(graph) < 2:
+ entrance = nx.minimum_node_cut(graph).pop()
print(f'{flname}: Detected chamber, entrance: {entrance}')
diff --git a/demo/benchmark_game.py b/demo/benchmark_game.py
index 1f5df3c6..cdc6dedc 100644
--- a/demo/benchmark_game.py
+++ b/demo/benchmark_game.py
@@ -1,8 +1,14 @@
#!/usr/bin/env python3
+import argparse
+import cProfile
+import functools
+import subprocess
+import timeit
+
from pelita.layout import parse_layout
from pelita.game import run_game
-from pelita.player import stopping_player
+from pelita.player import stopping_player, nq_random_player
LAYOUT="""
##################################
@@ -27,15 +33,41 @@ LAYOUT="""
layout = parse_layout(LAYOUT)
-def run():
- return run_game([stopping_player, stopping_player], max_rounds=10, layout_dict=layout)
+def run(teams, max_rounds):
+ return run_game(teams, max_rounds=max_rounds, layout_dict=layout, print_result=False, allow_exceptions=True, store_output=subprocess.DEVNULL)
+
+def parse_args():
+ parser = argparse.ArgumentParser(description='Benchmark pelita run_game')
+ parser.add_argument('--repeat', help="Number of repeats of timeit.", default=5, type=int)
+ parser.add_argument('--number', help="Number of iterations inside timeit.", default=10, type=int)
+ parser.add_argument('--max-rounds', help="Max rounds.", default=300, type=int)
+
+ parser.add_argument('--cprofile', help="Show cProfile output with test teams (int).", default=None, type=int)
+
+ return parser.parse_args()
if __name__ == '__main__':
- import timeit
- REPEAT = 5
- NUMBER = 10
- result = min(timeit.repeat(run, repeat=REPEAT, number=NUMBER))
- print("Fastest out of {}: {}".format(REPEAT, result))
-
- import cProfile
- cProfile.runctx("""run()""", globals(), locals())
+ args = parse_args()
+ REPEAT = args.repeat
+ NUMBER = args.number
+ MAX_ROUNDS = args.max_rounds
+
+ tests = [
+ ("Stopping", [stopping_player, stopping_player]),
+ ("NQ_Random", [nq_random_player, nq_random_player]),
+ ("Stopping (remote)", ["pelita/player/StoppingPlayer.py", "pelita/player/StoppingPlayer.py"]),
+ ("NQ_Random (remote)", ["pelita/player/RandomPlayers.py", "pelita/player/RandomPlayers.py"]),
+ ]
+
+ if args.cprofile is None:
+ print(f"Running {NUMBER} times with max {MAX_ROUNDS} rounds. Fastest out of {REPEAT}:")
+
+ for name, teams in tests:
+ result = min(timeit.repeat(functools.partial(run, teams=teams, max_rounds=MAX_ROUNDS), repeat=REPEAT, number=NUMBER))
+ print(f"{name:<20}: {result}")
+
+ else:
+ name, teams = tests[args.cprofile]
+ print(f"Running cProfile for teams {name} with max {MAX_ROUNDS} rounds:")
+ max_rounds = MAX_ROUNDS
+ cProfile.runctx("""run(teams, max_rounds)""", globals(), locals())
diff --git a/pelita/game.py b/pelita/game.py
index 04cc7e58..3c1c816b 100644
--- a/pelita/game.py
+++ b/pelita/game.py
@@ -268,6 +268,8 @@ def setup_game(team_specs, *, layout_dict, max_rounds=300, layout_name="", seed=
raise ValueError("Number of bots in layout must be 4.")
width, height = layout.wall_dimensions(layout_dict['walls'])
+ if not (width, height) == layout_dict['shape']:
+ raise ValueError(f"layout_dict['walls'] does not match layout_dict['shape'].")
for idx, pos in enumerate(layout_dict['bots']):
if pos in layout_dict['walls']:
@@ -300,8 +302,11 @@ def setup_game(team_specs, *, layout_dict, max_rounds=300, layout_name="", seed=
game_state = dict(
### The layout attributes
- #: Walls. List of (int, int)
- walls=layout_dict['walls'][:],
+ #: Walls. Set of (int, int)
+ walls=set(layout_dict['walls']),
+
+ #: Shape of the maze. (int, int)
+ shape=layout_dict['shape'],
#: Food per team. List of sets of (int, int)
food=food,
@@ -507,6 +512,7 @@ def prepare_bot_state(game_state, idx=None):
enemy_team = 1 - own_team
enemy_positions = game_state['bots'][enemy_team::2]
noised_positions = noiser(walls=game_state['walls'],
+ shape=game_state['shape'],
bot_position=bot_position,
enemy_positions=enemy_positions,
noise_radius=game_state['noise_radius'],
@@ -560,6 +566,7 @@ def prepare_bot_state(game_state, idx=None):
if bot_initialization:
bot_state.update({
'walls': game_state['walls'], # only in initial round
+ 'shape': game_state['shape'], # only in initial round
'seed': seed # only used in set_initial phase
})
@@ -739,6 +746,7 @@ def apply_move(gamestate, bot_position):
score = gamestate["score"]
food = gamestate["food"]
walls = gamestate["walls"]
+ shape = gamestate["shape"]
food = gamestate["food"]
n_round = gamestate["round"]
kills = gamestate["kills"]
@@ -756,7 +764,7 @@ def apply_move(gamestate, bot_position):
team_errors = gamestate["errors"][team]
# the allowed moves for the current bot
- legal_positions = get_legal_positions(walls, gamestate["bots"][gamestate["turn"]])
+ legal_positions = get_legal_positions(walls, shape, gamestate["bots"][gamestate["turn"]])
# unless we have already made an error, check if we made a legal move
if not (n_round, turn) in team_errors:
@@ -787,12 +795,11 @@ def apply_move(gamestate, bot_position):
_logger.info(f"Bot {turn} moves to {bot_position}.")
# then apply rules
# is bot in home or enemy territory
- x_walls = [i[0] for i in walls]
- boundary = max(x_walls) / 2 # float
+ boundary = gamestate['shape'][0] / 2
if team == 0:
bot_in_homezone = bot_position[0] < boundary
elif team == 1:
- bot_in_homezone = bot_position[0] > boundary
+ bot_in_homezone = bot_position[0] >= boundary
# update food list
if not bot_in_homezone:
if bot_position in food[1 - team]:
@@ -806,7 +813,7 @@ def apply_move(gamestate, bot_position):
for enemy_idx in killed_enemies:
_logger.info(f"Bot {turn} eats enemy bot {enemy_idx} at {bot_position}.")
score[team] = score[team] + KILL_POINTS
- init_positions = initial_positions(walls)
+ init_positions = initial_positions(walls, shape)
bots[enemy_idx] = init_positions[enemy_idx]
kills[turn] += 1
deaths[enemy_idx] += 1
@@ -818,7 +825,7 @@ def apply_move(gamestate, bot_position):
if len(enemies_on_target) > 0:
_logger.info(f"Bot {turn} was eaten by bots {enemies_on_target} at {bot_position}.")
score[1 - team] = score[1 - team] + KILL_POINTS
- init_positions = initial_positions(walls)
+ init_positions = initial_positions(walls, shape)
bots[turn] = init_positions[turn]
deaths[turn] += 1
kills[enemies_on_target[0]] += 1
diff --git a/pelita/gamestate_filters.py b/pelita/gamestate_filters.py
index 84c7eb7c..e43de6ce 100644
--- a/pelita/gamestate_filters.py
+++ b/pelita/gamestate_filters.py
@@ -5,7 +5,7 @@ import copy
### The main function
-def noiser(walls, bot_position, enemy_positions, noise_radius=5, sight_distance=5, rnd=None):
+def noiser(walls, shape, bot_position, enemy_positions, noise_radius=5, sight_distance=5, rnd=None):
"""Function to make bot positions noisy in a game state.
Applies uniform noise in maze space. Noise will only be applied if the
@@ -36,7 +36,7 @@ def noiser(walls, bot_position, enemy_positions, noise_radius=5, sight_distance=
Parameters
----------
- walls : list of (int, int)
+ walls : set of (int, int)
noise_radius : int, optional, default: 5
the radius for the uniform noise
sight_distance : int, optional, default: 5
@@ -67,7 +67,7 @@ def noiser(walls, bot_position, enemy_positions, noise_radius=5, sight_distance=
if cur_distance is None or cur_distance > sight_distance:
# If so then alter the position of the enemy
- new_pos, noisy_flag = alter_pos(b, noise_radius, rnd, walls)
+ new_pos, noisy_flag = alter_pos(b, noise_radius, rnd, walls, shape)
noised_positions[count] = new_pos
is_noisy[count] = noisy_flag
else:
@@ -80,26 +80,22 @@ def noiser(walls, bot_position, enemy_positions, noise_radius=5, sight_distance=
### The subfunctions
-def alter_pos(bot_pos, noise_radius, rnd, walls):
+def alter_pos(bot_pos, noise_radius, rnd, walls, shape):
""" alter the position """
- # extracting from walls the maximum width and height
- max_walls = max(walls)
- min_walls = min(walls)
-
# get a list of possible positions
x_min, x_max = bot_pos[0] - noise_radius, bot_pos[0] + noise_radius
y_min, y_max = bot_pos[1] - noise_radius, bot_pos[1] + noise_radius
- # filter them so the we return no positions outsided the maze
+ # filter them so that we return no positions outside the maze
if x_min < 0:
x_min = 1
- if x_max > max_walls[0]:
- x_max = max_walls[0]
+ if x_max >= shape[0]:
+ x_max = shape[0] - 1
if y_min < 0:
y_min = 1
- if y_max > max_walls[1]:
- y_max = max_walls[1]
+ if y_max >= shape[1]:
+ y_max = shape[1] - 1
possible_positions = [
(i, j)
diff --git a/pelita/layout.py b/pelita/layout.py
index a45a6f3e..3039bbc2 100644
--- a/pelita/layout.py
+++ b/pelita/layout.py
@@ -111,16 +111,18 @@ def parse_layout(layout_str, food=None, bots=None):
Return a dict
- {'walls': list_of_wall_coordinates,
+ {'walls': set_of_wall_coordinates,
'food' : list_of_food_coordinates,
- 'bots' : list_of_bot_coordinates in the order (a,x,b,y) }
+ 'bots' : list_of_bot_coordinates in the order (a,x,b,y),
+ 'shape': tuple of (height, width) of the layout}
In the example above:
- {'walls': [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 4), (2, 0),
+ {'walls': {(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 4), (2, 0),
(2, 4), (3, 0), (3, 2), (3, 4), (4, 0), (4, 2), (4, 4), (5, 0),
- (5, 4), (6, 0), (6, 4), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4)],
+ (5, 4), (6, 0), (6, 4), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4)},
'food': [(3, 3), (4, 1)],
- 'bots': [(1, 1), (6, 2), (1, 2), (6, 3)]}
+ 'bots': [(1, 1), (6, 2), (1, 2), (6, 3)],
+ 'shape': (8, 4)}
Additional food and bots can be passed:
@@ -135,7 +137,7 @@ def parse_layout(layout_str, food=None, bots=None):
food = []
# set empty default values
- lwalls = []
+ lwalls = set()
lfood = []
lbots = [None] * 4
@@ -190,7 +192,7 @@ def parse_layout(layout_str, food=None, bots=None):
# assign the char to the corresponding list
if char == '#':
# wall
- lwalls.append(coord)
+ lwalls.add(coord)
elif char == '.':
# food
lfood.append(coord)
@@ -212,7 +214,6 @@ def parse_layout(layout_str, food=None, bots=None):
missing_bots.append(BOT_I2N[i])
if missing_bots:
raise ValueError(f"Missing bot(s): {missing_bots}")
- lwalls.sort()
lfood.sort()
# if additional food was supplied, we add it
@@ -239,25 +240,27 @@ def parse_layout(layout_str, food=None, bots=None):
# build parsed layout, ensuring walls and food are sorted
parsed_layout = {
- 'walls': sorted(lwalls),
+ 'walls': lwalls,
'food': sorted(lfood),
- 'bots': lbots
+ 'bots': lbots,
+ 'shape': (width, height)
}
return parsed_layout
-def layout_as_str(*, walls, food=None, bots=None):
+def layout_as_str(*, walls, food=None, bots=None, shape=None):
"""Given a dictionary with walls, food and bots coordinates return a string layout representation
Example:
Given:
- {'walls': [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 4), (2, 0),
+ {'walls': {(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 4), (2, 0),
(2, 4), (3, 0), (3, 2), (3, 4), (4, 0), (4, 2), (4, 4), (5, 0),
- (5, 4), (6, 0), (6, 4), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4)],
+ (5, 4), (6, 0), (6, 4), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4)},
'food': [(3, 3), (4, 1)],
- 'bots': [(1, 1), (6, 2), (1, 2), (6, 3)]}
+ 'bots': [(1, 1), (6, 2), (1, 2), (6, 3)],
+ 'shape': (8, 4)}
Return:
########
@@ -268,10 +271,14 @@ def layout_as_str(*, walls, food=None, bots=None):
Overlapping items are discarded. When overlapping, walls take precedence over
bots, which take precedence over food.
+
+ The shape is optional. When it does not match the borders of the maze, a ValueError
+ is raised.
"""
- walls = sorted(walls)
- width = max(walls)[0] + 1
- height = max(walls)[1] + 1
+ width, height = wall_dimensions(walls)
+
+ if shape is not None and not (width, height) == shape:
+ raise ValueError(f"Given shape {shape} does not match width and height of layout {(width, height)}.")
# initialized empty containers
if food is None:
@@ -299,13 +306,14 @@ def layout_as_str(*, walls, food=None, bots=None):
def wall_dimensions(walls):
- """ Given a list of walls, returns a tuple of (width, height)."""
- width = max(walls)[0] + 1
- height = max(walls)[1] + 1
+ """ Given a list of walls, returns the shape of the maze as a tuple of (width, height)"""
+ max_elem = max(walls)
+ width = max_elem[0] + 1
+ height = max_elem[1] + 1
return (width, height)
-def initial_positions(walls):
+def initial_positions(walls, shape):
"""Calculate initial positions.
Given the list of walls, returns the free positions that are closest to the
@@ -314,8 +322,7 @@ def initial_positions(walls):
for judging what is closest. On equal distances, a smaller distance in the
x value is preferred.
"""
- width = max(walls)[0] + 1
- height = max(walls)[1] + 1
+ width, height = shape
left_start = (1, height - 2)
left = []
@@ -370,13 +377,13 @@ def initial_positions(walls):
return [left[0], right[0], left[1], right[1]]
-def get_legal_positions(walls, bot_position):
+def get_legal_positions(walls, shape, bot_position):
""" Returns all legal positions that a bot at `bot_position`
can go to.
Parameters
----------
- walls : list
+ walls : set of (int, int)
position of the walls of current layout.
bot_position: tuple
position of current bot.
@@ -391,7 +398,7 @@ def get_legal_positions(walls, bot_position):
ValueError
if bot_position invalid or on wall
"""
- width, height = wall_dimensions(walls)
+ width, height = shape
if not (0, 0) <= bot_position < (width, height):
raise ValueError(f"Position {bot_position} not inside maze ({width}x{height}).")
if bot_position in walls:
diff --git a/pelita/network.py b/pelita/network.py
index 7cd5f29c..0a444ef4 100644
--- a/pelita/network.py
+++ b/pelita/network.py
@@ -96,6 +96,14 @@ def bind_socket(socket, address, option_hint=None):
(option_hint,), file=sys.stderr)
raise
+
+class SetEncoder(json.JSONEncoder):
+ def default(self, obj):
+ if isinstance(obj, set):
+ return list(obj)
+ return json.JSONEncoder.default(self, obj)
+
+
def json_default_handler(o):
""" Pythons built-in json handler has problems converting numpy.in64
to json. By adding this method as a default= to json.dumps, we can
@@ -164,7 +172,7 @@ class ZMQConnection:
# race condition if a connection was closed between poll and send.
# NOBLOCK should raise, so we can catch that
message_obj = {"__uuid__": msg_id, "__action__": action, "__data__": data}
- json_message = json.dumps(message_obj)
+ json_message = json.dumps(message_obj, cls=SetEncoder)
try:
self.socket.send_unicode(json_message, flags=zmq.NOBLOCK)
except zmq.ZMQError as e:
@@ -275,7 +283,6 @@ class ZMQConnection:
def __repr__(self):
return "ZMQConnection(%r)" % self.socket
-
class ZMQPublisher:
""" Sets up a simple Publisher which sends all viewed events
over a zmq connection.
@@ -298,7 +305,7 @@ class ZMQPublisher:
info['gameover'] = True
_logger.debug(f"--#> [{action}] %r", info)
message = {"__action__": action, "__data__": data}
- as_json = json.dumps(message)
+ as_json = json.dumps(message, cls=SetEncoder)
self.socket.send_unicode(as_json)
def show_state(self, game_state):
diff --git a/pelita/player/team.py b/pelita/player/team.py
index dc693bf7..e2ded2fc 100644
--- a/pelita/player/team.py
+++ b/pelita/player/team.py
@@ -6,7 +6,6 @@ import random
import subprocess
import sys
import traceback
-from functools import reduce
from io import StringIO
from pathlib import Path
@@ -14,12 +13,31 @@ import zmq
from .. import layout
from ..exceptions import PlayerDisconnected, PlayerTimeout
-from ..layout import layout_as_str, parse_layout, wall_dimensions, BOT_I2N
+from ..layout import layout_as_str, BOT_I2N
from ..network import ZMQClientError, ZMQConnection, ZMQReplyTimeout, ZMQUnreachablePeer
_logger = logging.getLogger(__name__)
+def _ensure_list_tuples(list):
+ """ Ensures that an iterable is a list of position tuples. """
+ return [tuple(item) for item in list]
+
+def _ensure_set_tuples(set):
+ """ Ensures that an iterable is a set of position tuples. """
+ return {tuple(item) for item in set}
+
+
+def create_homezones(shape):
+ width, height = shape
+ return [
+ {(x, y) for x in range(0, width // 2)
+ for y in range(0, height)},
+ {(x, y) for x in range(width // 2, width)
+ for y in range(0, height)}
+ ]
+
+
class Team:
"""
Wraps a move function and forwards it the `set_initial`
@@ -78,7 +96,16 @@ class Team:
self._bot_track = [[], []]
# Store the walls, which are only transmitted once
- self._walls = game_state['walls']
+ self._walls = _ensure_set_tuples(game_state['walls'])
+
+ # Store the shape, which is only transmitted once
+ self._shape = tuple(game_state['shape'])
+
+ # Cache the initial positions so that we don’t have to calculate them at each step
+ self._initial_positions = layout.initial_positions(self._walls, self._shape)
+
+ # Cache the homezone so that we don’t have to create it at each step
+ self._homezone = create_homezones(self._shape)
return self.team_name
@@ -98,6 +125,9 @@ class Team:
move : dict
"""
me = make_bots(walls=self._walls,
+ shape=self._shape,
+ initial_positions=self._initial_positions,
+ homezone=self._homezone,
team=game_state['team'],
enemy=game_state['enemy'],
round=game_state['round'],
@@ -107,7 +137,7 @@ class Team:
team = me._team
for idx, mybot in enumerate(team):
- # If a bot has been killed, we reset it’s bot track
+ # If a bot has been killed, we reset its bot track
if mybot.was_killed:
self._bot_track[idx] = []
@@ -117,7 +147,7 @@ class Team:
for idx, mybot in enumerate(team):
# If the track of any bot is empty,
- # Add its current position
+ # add its current position
if me._bot_turn != idx:
self._bot_track[idx].append(mybot.position)
@@ -397,26 +427,13 @@ def make_team(team_spec, team_name=None, zmq_context=None, idx=None, store_outpu
return team_player, zmq_context
-def create_homezones(walls):
- width = max(walls)[0]+1
- height = max(walls)[1]+1
- return [
- [(x, y) for x in range(0, width // 2)
- for y in range(0, height)],
- [(x, y) for x in range(width // 2, width)
- for y in range(0, height)]
- ]
-
-def _ensure_tuples(list):
- """ Ensures that an iterable is a list of position tuples. """
- return [tuple(item) for item in list]
-
class Bot:
def __init__(self, *, bot_index,
is_on_team,
position,
initial_position,
walls,
+ shape,
homezone,
food,
score,
@@ -443,10 +460,11 @@ class Bot:
self.random = random
self.position = tuple(position)
self._initial_position = tuple(initial_position)
- self.walls = _ensure_tuples(walls)
+ self.walls = walls
- self.homezone = _ensure_tuples(homezone)
- self.food = _ensure_tuples(food)
+ self.homezone = homezone
+ self.food = food
+ self.shape = shape
self.score = score
self.kills = kills
self.deaths = deaths
@@ -554,8 +572,7 @@ class Bot:
def _repr_html_(self):
""" Jupyter-friendly representation. """
bot = self
- width = max(bot.walls)[0] + 1
- height = max(bot.walls)[1] + 1
+ width, height = bot.shape
with StringIO() as out:
out.write("<table>")
@@ -589,8 +606,6 @@ class Bot:
def __str__(self):
bot = self
- width = max(bot.walls)[0] + 1
- height = max(bot.walls)[1] + 1
if bot.is_blue:
blue = bot if not bot.turn else bot.other
@@ -628,9 +643,10 @@ class Bot:
with StringIO() as out:
out.write(header)
- layout = layout_as_str(walls=bot.walls[:],
+ layout = layout_as_str(walls=bot.walls.copy(),
food=bot.food + bot.enemy[0].food,
- bots=bot_positions)
+ bots=bot_positions,
+ shape=bot.shape)
out.write(str(layout))
out.write(footer)
@@ -638,14 +654,12 @@ class Bot:
# def __init__(self, *, bot_index, position, initial_position, walls, homezone, food, is_noisy, score, random, round, is_blue):
-def make_bots(*, walls, team, enemy, round, bot_turn, rng):
+def make_bots(*, walls, shape, initial_positions, homezone, team, enemy, round, bot_turn, rng):
bots = {}
team_index = team['team_index']
enemy_index = enemy['team_index']
- homezone = create_homezones(walls)
- initial_positions = layout.initial_positions(walls)
team_initial_positions = initial_positions[team_index::2]
enemy_initial_positions = initial_positions[enemy_index::2]
@@ -659,8 +673,9 @@ def make_bots(*, walls, team, enemy, round, bot_turn, rng):
was_killed=team['bot_was_killed'][idx],
is_noisy=False,
error_count=team['error_count'],
- food=team['food'],
+ food=_ensure_list_tuples(team['food']),
walls=walls,
+ shape=shape,
round=round,
bot_turn=bot_turn,
bot_char=BOT_I2N[team_index + idx*2],
@@ -683,8 +698,9 @@ def make_bots(*, walls, team, enemy, round, bot_turn, rng):
was_killed=enemy['bot_was_killed'][idx],
is_noisy=enemy['is_noisy'][idx],
error_count=enemy['error_count'],
- food=enemy['food'],
+ food=_ensure_list_tuples(enemy['food']),
walls=walls,
+ shape=shape,
round=round,
bot_char = BOT_I2N[team_index + idx*2],
random=rng,
@@ -700,5 +716,3 @@ def make_bots(*, walls, team, enemy, round, bot_turn, rng):
bots['enemy'] = enemy_bots
return team_bots[bot_turn]
-
-
diff --git a/pelita/ui/tk_canvas.py b/pelita/ui/tk_canvas.py
index 671ac456..025f7e5d 100644
--- a/pelita/ui/tk_canvas.py
+++ b/pelita/ui/tk_canvas.py
@@ -8,6 +8,7 @@ import tkinter
import tkinter.font
from ..game import next_round_turn
+from ..player.team import _ensure_list_tuples
from .tk_sprites import BotSprite, Food, Wall, col
from .tk_utils import wm_delete_window_handler
from .tk_sprites import BotSprite, Food, Wall, RED, BLUE, YELLOW, GREY, BROWN
@@ -15,10 +16,6 @@ from .. import layout
_logger = logging.getLogger(__name__)
-def _ensure_tuples(list):
- """ Ensures that an iterable is a list of position tuples. """
- return [tuple(item) for item in list]
-
def guess_size(display_string, bounding_width, bounding_height, rel_size=0):
no_lines = display_string.count("\n") + 1
@@ -341,8 +338,7 @@ class TkApplication:
def init_mesh(self, game_state):
- width = max(game_state['walls'])[0] + 1
- height = max(game_state['walls'])[1] + 1
+ width, height = game_state['shape']
if self.geometry is None:
screensize = (
@@ -425,8 +421,8 @@ class TkApplication:
self.size_changed = False
def draw_universe(self, game_state):
- self.mesh_graph.num_x = max(game_state['walls'])[0] + 1
- self.mesh_graph.num_y = max(game_state['walls'])[1] + 1
+ self.mesh_graph.num_x = game_state['shape'][0]
+ self.mesh_graph.num_y = game_state['shape'][1]
self.draw_grid()
self.draw_selected(game_state)
@@ -578,7 +574,7 @@ class TkApplication:
has_food = pos in game_state['food']
is_wall = pos in game_state['walls']
bots = [idx for idx, bot in enumerate(game_state['bots']) if bot==pos]
- if pos[0] < (max(game_state['walls'])[0] + 1) // 2:
+ if pos[0] <= (game_state['shape'][0] // 2):
zone = "blue"
else:
zone = "red"
@@ -796,9 +792,10 @@ class TkApplication:
skip_request = False
self._observed_steps.add(step)
# ensure walls, foods and bots positions are list of tuples
- game_state['walls'] = _ensure_tuples(game_state['walls'])
- game_state['food'] = _ensure_tuples(game_state['food'])
- game_state['bots'] = _ensure_tuples(game_state['bots'])
+ game_state['walls'] = _ensure_list_tuples(game_state['walls'])
+ game_state['food'] = _ensure_list_tuples(game_state['food'])
+ game_state['bots'] = _ensure_list_tuples(game_state['bots'])
+ game_state['shape'] = tuple(game_state['shape'])
self.update(game_state)
if self._stop_after is not None:
if self._stop_after == 0:
diff --git a/pelita/utils.py b/pelita/utils.py
index d92dfad5..b56f3c72 100644
--- a/pelita/utils.py
+++ b/pelita/utils.py
@@ -1,11 +1,11 @@
import random
-import networkx
+import networkx as nx
-from .player.team import make_bots
+from .player.team import make_bots, create_homezones
from .layout import (get_random_layout, get_layout_by_name, get_available_layouts,
- parse_layout, BOT_N2I)
+ parse_layout, BOT_N2I, initial_positions, wall_dimensions)
RNG = random.Random()
@@ -14,8 +14,8 @@ def walls_to_graph(walls):
Parameters
----------
- walls : list[(x0,y0), (x1,y1), ...]
- a list of wall coordinates
+ walls : set[(x0,y0), (x1,y1), ...]
+ a set of wall coordinates
Returns
-------
@@ -32,10 +32,9 @@ def walls_to_graph(walls):
adjacent squares. Adjacent means that you can go from one square to one of
its adjacent squares by making ore single step (up, down, left, or right).
"""
- graph = networkx.Graph()
- extreme = max(walls)
- width = extreme[0] + 1
- height = extreme[1] + 1
+ graph = nx.Graph()
+ width, height = wall_dimensions(walls)
+
for x in range(width):
for y in range(height):
if (x, y) not in walls:
@@ -110,7 +109,7 @@ def run_background_game(*, blue_move, red_move, layout=None, max_rounds=300, see
game_state : dict
the final game state as a dictionary. Dictionary keys are:
- 'seed' : the seed used to initialize the random number generator
- - 'walls' : list of walls coordinates for the layout
+ - 'walls' : set of wall coordinates for the layout
- 'layout' : the name of the used layout
- 'round' : the round at which the game was over
- 'draw' : True if the game ended in a draw
@@ -246,7 +245,7 @@ def setup_test_game(*, layout, is_blue=True, round=None, score=None, seed=None,
layout, layout_name = _parse_layout_arg(layout=layout, food=food, bots=bots)
- width = max(layout['walls'])[0] + 1
+ width, height = layout['shape']
def split_food(width, food):
team_food = [set(), set()]
@@ -296,7 +295,10 @@ def setup_test_game(*, layout, is_blue=True, round=None, score=None, seed=None,
'name': "red" if is_blue else "blue"
}
- bot = make_bots(walls=layout['walls'][:],
+ bot = make_bots(walls=layout['walls'].copy(),
+ shape=layout['shape'],
+ initial_positions=initial_positions(layout['walls'], layout['shape']),
+ homezone=create_homezones(layout['shape']),
team=team,
enemy=enemy,
round=round,
diff --git a/pelita/viewer.py b/pelita/viewer.py
index 73ab01b9..c9d6c414 100644
--- a/pelita/viewer.py
+++ b/pelita/viewer.py
@@ -6,6 +6,7 @@ import logging
import zmq
from . import layout
+from .network import SetEncoder
_logger = logging.getLogger(__name__)
@@ -128,7 +129,7 @@ class ReplyToViewer:
def _send(self, message):
socks = dict(self.pollout.poll(300))
if socks.get(self.sock) == zmq.POLLOUT:
- as_json = json.dumps(message)
+ as_json = json.dumps(message, cls=SetEncoder)
self.sock.send_unicode(as_json, flags=zmq.NOBLOCK)
def show_state(self, game_state):
@@ -142,7 +143,7 @@ class ReplayWriter:
self.stream = stream
def _send(self, message):
- as_json = json.dumps(message)
+ as_json = json.dumps(message, cls=SetEncoder)
self.stream.write(as_json)
# We use 0x04 (EOT) as a separator between the events.
# The additional newline is for improved readability
|
ASPP__pelita-798
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/game.py:prepare_bot_state"
],
"edited_modules": [
"pelita/game.py:prepare_bot_state"
]
},
"file": "pelita/game.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/team.py:Bot.__init__",
"pelita/team.py:make_bots"
],
"edited_modules": [
"pelita/team.py:Bot",
"pelita/team.py:make_bots"
]
},
"file": "pelita/team.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/utils.py:setup_test_game"
],
"edited_modules": [
"pelita/utils.py:setup_test_game"
]
},
"file": "pelita/utils.py"
}
] |
ASPP/pelita
|
245a9ca445eccda07998cb58fbee340308d425a7
|
make the cumulative time counter available to clients
The `Bot` object should have an attribute `time` where the cumulative time for the team shown in the GUI is made available. This is useful for example when benchmarking different strategies. There's no way at the moment to programmatically access that value, as far as I could see.
Of course the client could time itself, but this has its own pitfalls. So it's better to just make that value available, even if we all know it's not super precise...
|
diff --git a/pelita/game.py b/pelita/game.py
index 6cbacc56..efc51f3a 100644
--- a/pelita/game.py
+++ b/pelita/game.py
@@ -555,7 +555,8 @@ def prepare_bot_state(game_state, idx=None):
'bot_was_killed': game_state['bot_was_killed'][own_team::2],
'error_count': len(game_state['errors'][own_team]),
'food': list(game_state['food'][own_team]),
- 'name': game_state['team_names'][own_team]
+ 'name': game_state['team_names'][own_team],
+ 'team_time': game_state['team_time'][own_team]
}
enemy_state = {
@@ -568,7 +569,8 @@ def prepare_bot_state(game_state, idx=None):
'bot_was_killed': game_state['bot_was_killed'][enemy_team::2],
'error_count': 0, # TODO. Could be left out for the enemy
'food': list(game_state['food'][enemy_team]),
- 'name': game_state['team_names'][enemy_team]
+ 'name': game_state['team_names'][enemy_team],
+ 'team_time': game_state['team_time'][enemy_team]
}
bot_state = {
diff --git a/pelita/team.py b/pelita/team.py
index dab0930c..02c66bca 100644
--- a/pelita/team.py
+++ b/pelita/team.py
@@ -522,6 +522,7 @@ class Bot:
bot_char,
is_blue,
team_name,
+ team_time,
error_count,
is_noisy,
bot_turn=None):
@@ -551,6 +552,7 @@ class Bot:
self.char = bot_char
self.is_blue = is_blue
self.team_name = team_name
+ self.team_time = team_time
self.error_count = error_count
self.is_noisy = is_noisy
self.graph = graph
@@ -745,7 +747,8 @@ def make_bots(*, walls, shape, initial_positions, homezone, team, enemy, round,
initial_position=team_initial_positions[idx],
is_blue=team_index % 2 == 0,
homezone=homezone[team_index],
- team_name=team['name'])
+ team_name=team['name'],
+ team_time=team['team_time'])
b._bots = bots
team_bots.append(b)
@@ -770,7 +773,8 @@ def make_bots(*, walls, shape, initial_positions, homezone, team, enemy, round,
initial_position=enemy_initial_positions[idx],
is_blue=enemy_index % 2 == 0,
homezone=homezone[enemy_index],
- team_name=enemy['name'])
+ team_name=enemy['name'],
+ team_time=enemy['team_time'])
b._bots = bots
enemy_bots.append(b)
diff --git a/pelita/utils.py b/pelita/utils.py
index 6db44810..10f15473 100644
--- a/pelita/utils.py
+++ b/pelita/utils.py
@@ -245,7 +245,8 @@ def setup_test_game(*, layout, is_blue=True, round=None, score=None, seed=None,
'bot_was_killed' : [False]*2,
'error_count': 0,
'food': food[team_index],
- 'name': "blue" if is_blue else "red"
+ 'name': "blue" if is_blue else "red",
+ 'team_time': 0.0,
}
enemy = {
'bot_positions': enemy_positions,
@@ -257,7 +258,8 @@ def setup_test_game(*, layout, is_blue=True, round=None, score=None, seed=None,
'error_count': 0,
'food': food[enemy_index],
'is_noisy': is_noisy_enemy,
- 'name': "red" if is_blue else "blue"
+ 'name': "red" if is_blue else "blue",
+ 'team_time': 0.0,
}
bot = make_bots(walls=layout['walls'],
|
ASPP__pelita-815
|
[
{
"changes": {
"added_entities": [
"contrib/ci_engine.py:CI_Engine.get_team_name",
"contrib/ci_engine.py:DB_Wrapper.add_team_name",
"contrib/ci_engine.py:DB_Wrapper.get_team_name"
],
"added_modules": null,
"edited_entities": [
"contrib/ci_engine.py:CI_Engine.load_players",
"contrib/ci_engine.py:CI_Engine.pretty_print_results",
"contrib/ci_engine.py:DB_Wrapper.create_tables"
],
"edited_modules": [
"contrib/ci_engine.py:CI_Engine",
"contrib/ci_engine.py:DB_Wrapper"
]
},
"file": "contrib/ci_engine.py"
}
] |
ASPP/pelita
|
6e70daf7313ca878e3a46240ca6a20811024e9db
|
Add team name in CI table
Remote players only show their team names making comparisons harder.
Conversely, the remote player should/could also include the spec name.
|
diff --git a/contrib/ci_engine.py b/contrib/ci_engine.py
index c1cb84d0..f44194f1 100755
--- a/contrib/ci_engine.py
+++ b/contrib/ci_engine.py
@@ -120,11 +120,15 @@ class CI_Engine:
self.dbwrapper.add_player(pname, new_hash)
for player in self.players:
+ path = player['path']
+ pname = player['name']
try:
- check_team(player['path'])
+ _logger.debug('Querying team name for %s.' % pname)
+ team_name = check_team(player['path'])
+ self.dbwrapper.add_team_name(pname, team_name)
except ZMQClientError as e:
e_type, e_msg = e.args
- _logger.debug(f'Could not import {pname} ({e_type}): {e_msg}')
+ _logger.debug(f'Could not import {player} at path {path} ({e_type}): {e_msg}')
player['error'] = e.args
def run_game(self, p1, p2):
@@ -254,7 +258,6 @@ class CI_Engine:
elif r == -1: draw += 1
return win, loss, draw
-
def get_errorcount(self, idx):
"""Gets the error count for team idx
@@ -273,6 +276,14 @@ class CI_Engine:
error_count, fatalerror_count = self.dbwrapper.get_errorcount(p_name)
return error_count, fatalerror_count
+ def get_team_name(self, idx):
+ """Get last registered team name.
+
+ team_name : string
+ """
+
+ p_name = self.players[idx]['name']
+ return self.dbwrapper.get_team_name(p_name)
def gen_elo(self):
k = 32
@@ -351,8 +362,12 @@ class CI_Engine:
for idx, p in enumerate(good_players):
win, loss, draw = self.get_results(idx)
error_count, fatalerror_count = self.get_errorcount(idx)
+ try:
+ team_name = self.get_team_name(idx)
+ except ValueError:
+ team_name = None
score = 0 if (win+loss+draw) == 0 else (win-loss) / (win+loss+draw)
- result.append([score, win, draw, loss, p['name'], error_count, fatalerror_count])
+ result.append([score, win, draw, loss, p['name'], team_name, error_count, fatalerror_count])
wdl = f"{win:3d},{draw:3d},{loss:3d}"
try:
@@ -392,8 +407,9 @@ class CI_Engine:
elo = self.gen_elo()
result.sort(reverse=True)
- for [score, win, draw, loss, name, error_count, fatalerror_count] in result:
+ for [score, win, draw, loss, name, team_name, error_count, fatalerror_count] in result:
style = "bold" if name in highlight else None
+ name = f"{name} ({team_name})" if team_name else f"{name}"
table.add_row(
name,
f"{win+draw+loss}",
@@ -440,15 +456,20 @@ class DB_Wrapper:
"""
self.cursor.execute("""
+ CREATE TABLE IF NOT EXISTS players
+ (name text PRIMARY KEY, hash text)
+ """)
+ self.cursor.execute("""
+ CREATE TABLE IF NOT EXISTS team_names
+ (name text PRIMARY KEY, team_name text,
+ FOREIGN KEY(name) REFERENCES players(name) ON DELETE CASCADE)
+ """)
+ self.cursor.execute("""
CREATE TABLE IF NOT EXISTS games
(player1 text, player2 text, result int, final_state text, stdout text, stderr text,
FOREIGN KEY(player1) REFERENCES players(name) ON DELETE CASCADE,
FOREIGN KEY(player2) REFERENCES players(name) ON DELETE CASCADE)
""")
- self.cursor.execute("""
- CREATE TABLE IF NOT EXISTS players
- (name text PRIMARY KEY, hash text)
- """)
self.connection.commit()
def get_players(self):
@@ -504,6 +525,24 @@ class DB_Wrapper:
except sqlite3.IntegrityError:
raise ValueError('Player %s already exists in database' % name)
+ def add_team_name(self, name, team_name):
+ """Adds or updates team name to database
+
+ Parameters
+ ----------
+ name : str
+ team_name : str
+
+ """
+ try:
+ self.cursor.execute("""
+ INSERT OR REPLACE INTO team_names
+ VALUES (?, ?)
+ """, [name, team_name])
+ self.connection.commit()
+ except sqlite3.IntegrityError:
+ raise ValueError('Cannot add team name for %s' % name)
+
def remove_player(self, pname):
"""Remove a player from the database.
@@ -573,6 +612,27 @@ class DB_Wrapper:
return relevant_results
+ def get_team_name(self, p_name):
+ """Gets the last registered team name of p_name.
+
+ Parameters
+ ----------
+ p_name : str
+ the name of the player
+
+ Returns
+ -------
+ team_name : str
+
+ """
+ self.cursor.execute("""
+ SELECT team_name FROM team_names
+ WHERE name = ?""", (p_name,))
+ res = self.cursor.fetchone()
+ if res is None:
+ raise ValueError('Player %s does not exist in database.' % p_name)
+ return res[0]
+
def get_game_count(self, p1_name, p2_name=None):
"""Get number of games involving player1 (AND player2 if specified).
|
ASPP__pelita-863
|
[
{
"changes": {
"added_entities": [
"pelita/team.py:Bot.__repr__"
],
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"pelita/team.py:Bot"
]
},
"file": "pelita/team.py"
}
] |
ASPP/pelita
|
ab9217f298fa4897b06e5e9e9e7fad7e29ba7114
|
Better Bot repr
For reference, this is the current `repr(bot)`:
<pelita.team.Bot object at 0x102778b90>
This is `str(bot)`:
```
Playing on red side. Current turn: 1. Bot: y. Round: 1, score: 0:0. timeouts: 0:0
################################
#. . #. . . #.y#
# # #### ### . # . .x#
# . ##..# ######### #
#. # # #.### . .. .. .# #
######## #. # #### #.### ##
# .# #. # .# . # #
# ## ##. ##..# # .# # ##
## # #. # #..## .## ## #
#a # . #. # .# #. #
##b###.# #### # .# ########
# #. .. .. . ###.# # # .#
# ######### #..## . #
# . . # . ### #### # #
# .# . . .# . .#
################################
Bots: {'a': (1, 9), 'x': (30, 2), 'b': (2, 10), 'y': (30, 1)}
Noisy: {'a': True, 'x': False, 'b': True, 'y': False}
Food: [(30, 14), (21, 10), (24, 4), (20, 14), (26, 1), (24, 7), (27, 4), (29, 9), (18, 6), (21, 8), (20, 12), (21, 4), (25, 4), (27, 2), (18, 4), (24, 14), (17, 7), (18, 7), (29, 1), (20, 4), (27, 14), (21, 9), (21, 12), (18, 11), (24, 6), (25, 5), (29, 2), (19, 2), (26, 12), (30, 11), (11, 1), (10, 5), (10, 11), (13, 4), (12, 13), (2, 13), (7, 9), (10, 6), (6, 10), (10, 3), (4, 1), (13, 11), (11, 11), (2, 14), (13, 8), (14, 8), (7, 1), (4, 13), (6, 11), (5, 14), (1, 1), (11, 3), (10, 7), (1, 4), (13, 9), (2, 6), (5, 3), (4, 11), (7, 11), (7, 8)]
```
At the least I think it should be something like:
<Bot: y (red), (30, 1), turn: 1, round: 1>
|
diff --git a/pelita/team.py b/pelita/team.py
index a3ef1138..aea97327 100644
--- a/pelita/team.py
+++ b/pelita/team.py
@@ -726,6 +726,9 @@ class Bot:
out.write(footer)
return out.getvalue()
+ def __repr__(self):
+ return f'<Bot: {self.char} ({"blue" if self.is_blue else "red"}), {self.position}, turn: {self.turn}, round: {self.round}>'
+
# def __init__(self, *, bot_index, position, initial_position, walls, homezone, food, is_noisy, score, random, round, is_blue):
def make_bots(*, walls, shape, initial_positions, homezone, team, enemy, round, bot_turn, rng, graph):
|
ASPP__pelita-875
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"pelita/utils.py:run_background_game"
],
"edited_modules": [
"pelita/utils.py:run_background_game"
]
},
"file": "pelita/utils.py"
}
] |
ASPP/pelita
|
68af15d8d4199882d32bb4ede363195e2c5b5a99
|
run_background_game breaks when layout= is passed
```
def test_run_background_game_with_layout():
test_layout = (
""" ##################
#a#. . # . #
#b##### #####x#
# . # . .#y#
################## """)
result = utils.run_background_game(blue_move=stopping_player, red_move=stopping_player, layout=test_layout)
```
```
if layout is None:
layout_dict = generate_maze(rng=rng)
else:
> layout_dict = parse_layout(layout, food=food, bots=bots)
E NameError: name 'food' is not defined
pelita/utils.py:104: NameError
```
|
diff --git a/pelita/utils.py b/pelita/utils.py
index c5bdf54c..1f3bec36 100644
--- a/pelita/utils.py
+++ b/pelita/utils.py
@@ -104,7 +104,7 @@ def run_background_game(*, blue_move, red_move, layout=None, max_rounds=300, see
if layout is None:
layout_dict = generate_maze(rng=rng)
else:
- layout_dict = parse_layout(layout, food=food, bots=bots)
+ layout_dict = parse_layout(layout)
game_state = run_game((blue_move, red_move), layout_dict=layout_dict,
max_rounds=max_rounds, rng=rng,
|
AVEgame__AVE-108
|
[
{
"changes": {
"added_entities": [
"ave/components/numbers.py:Number.get_all_variables",
"ave/components/numbers.py:Constant.get_all_variables",
"ave/components/numbers.py:Sum.get_all_variables",
"ave/components/numbers.py:Product.get_all_variables",
"ave/components/numbers.py:Division.get_all_variables",
"ave/components/numbers.py:Negative.get_all_variables",
"ave/components/numbers.py:Variable.get_all_variables",
"ave/components/numbers.py:Random.get_all_variables"
],
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"ave/components/numbers.py:Number",
"ave/components/numbers.py:Constant",
"ave/components/numbers.py:Sum",
"ave/components/numbers.py:Product",
"ave/components/numbers.py:Division",
"ave/components/numbers.py:Negative",
"ave/components/numbers.py:Variable",
"ave/components/numbers.py:Random"
]
},
"file": "ave/components/numbers.py"
},
{
"changes": {
"added_entities": [
"ave/components/requirements.py:Requirement.get_all",
"ave/components/requirements.py:RequiredItem.get_all",
"ave/components/requirements.py:RequiredNumber.get_all",
"ave/components/requirements.py:Or.get_all",
"ave/components/requirements.py:And.get_all",
"ave/components/requirements.py:Not.get_all",
"ave/components/requirements.py:Satisfied.get_all"
],
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"ave/components/requirements.py:Requirement",
"ave/components/requirements.py:RequiredItem",
"ave/components/requirements.py:RequiredNumber",
"ave/components/requirements.py:Or",
"ave/components/requirements.py:And",
"ave/components/requirements.py:Not",
"ave/components/requirements.py:Satisfied"
]
},
"file": "ave/components/requirements.py"
}
] |
AVEgame/AVE
|
29c1a6f2f58198e3af2bde3b457af6cf8053b6af
|
Write code to run detailed checks that a game works
Put this in `ave.test`. It can then be used by the AVE pytest tests, and for AVEgame/AVE-usergames#2
|
diff --git a/ave/components/numbers.py b/ave/components/numbers.py
index 19fe14d..e321b64 100644
--- a/ave/components/numbers.py
+++ b/ave/components/numbers.py
@@ -10,6 +10,10 @@ class Number:
"""Get the value of the Number."""
raise NotImplementedError()
+ def get_all_variables(self):
+ """Get a list of all variables used in this expression."""
+ raise NotImplementedError()
+
class Constant(Number):
"""A constant."""
@@ -22,6 +26,10 @@ class Constant(Number):
"""Get the value of the Number."""
return self.value
+ def get_all_variables(self):
+ """Get a list of all variables used in this expression."""
+ return []
+
class Sum(Number):
"""The sum of multiple Numbers."""
@@ -34,6 +42,13 @@ class Sum(Number):
"""Get the value of the Number."""
return sum(i.get_value(character) for i in self.items)
+ def get_all_variables(self):
+ """Get a list of all variables used in this expression."""
+ out = []
+ for i in self.items:
+ out += i.get_all_variables()
+ return out
+
class Product(Number):
"""The product of multiple Numbers."""
@@ -49,6 +64,13 @@ class Product(Number):
out *= i.get_value(character)
return out
+ def get_all_variables(self):
+ """Get a list of all variables used in this expression."""
+ out = []
+ for i in self.items:
+ out += i.get_all_variables()
+ return out
+
class Division(Number):
"""The result of a division."""
@@ -65,6 +87,13 @@ class Division(Number):
out /= i.get_value(character)
return out
+ def get_all_variables(self):
+ """Get a list of all variables used in this expression."""
+ out = []
+ for i in self.items:
+ out += i.get_all_variables()
+ return out
+
class Negative(Number):
"""The negative of another Number."""
@@ -77,6 +106,10 @@ class Negative(Number):
"""Get the value of the Number."""
return -self.item.get_value(character)
+ def get_all_variables(self):
+ """Get a list of all variables used in this expression."""
+ return self.item.get_all_variables()
+
class Variable(Number):
"""The value of a variable."""
@@ -89,6 +122,10 @@ class Variable(Number):
"""Get the value of the Number."""
return character.numbers[self.item]
+ def get_all_variables(self):
+ """Get a list of all variables used in this expression."""
+ return [self.item]
+
class Random(Number):
"""A random number."""
@@ -111,3 +148,7 @@ class Random(Number):
end = self.end.get_value(character)
size = end - start
return start + random.random() * size
+
+ def get_all_variables(self):
+ """Get a list of all variables used in this expression."""
+ return self.start.get_all_variables() + self.end.get_all_variables()
diff --git a/ave/components/requirements.py b/ave/components/requirements.py
index 4eb410f..b859c2e 100644
--- a/ave/components/requirements.py
+++ b/ave/components/requirements.py
@@ -10,6 +10,10 @@ class Requirement:
"""Check if the character satisifies this."""
raise NotImplementedError()
+ def get_all(self):
+ """Get all items involved in this requirement."""
+ raise NotImplementedError()
+
class RequiredItem(Requirement):
"""The character must have an item."""
@@ -22,6 +26,10 @@ class RequiredItem(Requirement):
"""Check if the character satisifies this."""
return character.has(self.item)
+ def get_all(self):
+ """Get all items involved in this requirement."""
+ return [self.item]
+
class RequiredNumber(Requirement):
"""A numerical variable must satisfy a condition."""
@@ -47,6 +55,10 @@ class RequiredNumber(Requirement):
if self.sign == "=" or self.sign == "==":
return v1 == v2
+ def get_all(self):
+ """Get all items involved in this requirement."""
+ return self.v1.get_all_variables() + self.v1.get_all_variables()
+
class Or(Requirement):
"""One of a set of Requirements must be satisfied."""
@@ -62,6 +74,13 @@ class Or(Requirement):
return True
return False
+ def get_all(self):
+ """Get all items involved in this requirement."""
+ out = []
+ for i in self.items:
+ out += i.get_all()
+ return out
+
class And(Requirement):
"""A set of Requirements must all be satisfied."""
@@ -77,6 +96,13 @@ class And(Requirement):
return False
return True
+ def get_all(self):
+ """Get all items involved in this requirement."""
+ out = []
+ for i in self.items:
+ out += i.get_all()
+ return out
+
class Not(Requirement):
"""The negation of another Requirement."""
@@ -89,6 +115,10 @@ class Not(Requirement):
"""Check if the character satisifies this."""
return not self.item.has(character)
+ def get_all(self):
+ """Get all items involved in this requirement."""
+ return self.item.get_all()
+
class Satisfied(Requirement):
"""This requirement is always satisfied."""
@@ -96,3 +126,7 @@ class Satisfied(Requirement):
def has(self, character):
"""Check if the character satisifies this."""
return True
+
+ def get_all(self):
+ """Get all items involved in this requirement."""
+ return []
|
AVEgame__AVE-113
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"ave/ave.py:AVE.get_download_menu"
],
"edited_modules": [
"ave/ave.py:AVE"
]
},
"file": "ave/ave.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"ave/parsing/game_loader.py:load_library_json",
"ave/parsing/game_loader.py:load_game_from_library"
],
"edited_modules": [
"ave/parsing/game_loader.py:load_library_json",
"ave/parsing/game_loader.py:load_game_from_library"
]
},
"file": "ave/parsing/game_loader.py"
}
] |
AVEgame/AVE
|
b39a5ed00692e456e4d2533cde44e46830cc90a2
|
Check that running AVE version is high enough to play library games
I think I already did this, but needs testing.
|
diff --git a/ave/ave.py b/ave/ave.py
index 52fb295..cb4a94d 100644
--- a/ave/ave.py
+++ b/ave/ave.py
@@ -135,16 +135,12 @@ class AVE:
A list of the title, author and local url for each game.
"""
try:
- the_json = load_library_json()
+ library = load_library_json()
except AVENoInternet:
self.no_internet()
raise AVEToMenu
- menu_items = []
- for key, value in the_json.items():
- if 'user/' in key:
- menu_items.append([value['title'], value['author'],
- key])
- return menu_items
+ return [(game["title"], game["author"], i)
+ for i, game in enumerate(library)]
def show_download_menu(self):
"""Show a menu of games from the online library."""
diff --git a/ave/parsing/game_loader.py b/ave/parsing/game_loader.py
index 1ddf398..ce94d9f 100644
--- a/ave/parsing/game_loader.py
+++ b/ave/parsing/game_loader.py
@@ -4,6 +4,7 @@ import re
import json
import urllib.request
from ..game import Game
+from .. import config
from ..exceptions import AVENoInternet
from .string_functions import clean
from .file_parsing import parse_room, parse_item
@@ -16,9 +17,14 @@ def load_library_json():
global library_json
try:
if library_json is None:
+ library_json = []
with urllib.request.urlopen(
- "http://avegame.co.uk/gamelist.json") as f:
- library_json = json.load(f)
+ "https://avegame.co.uk/gamelist.json") as f:
+ for game in json.load(f):
+ game["ave_version"] = tuple(game["ave_version"])
+ if game["user"]:
+ if game["ave_version"] <= config.version_tuple:
+ library_json.append(game)
except: # noqa: E722
raise AVENoInternet
return library_json
@@ -79,13 +85,14 @@ def load_game_from_file(file, filename=None):
version=version, ave_version=ave_version)
-def load_game_from_library(url):
+def load_game_from_library(n):
"""Load the metadata of a game from the online library."""
- info = load_library_json()[url]
- return Game(url="http://avegame.co.uk/download/" + url,
+ info = load_library_json()[n]
+ print(info)
+ return Game(url="https://avegame.co.uk/download/user/" + info["filename"],
title=info["title"], description=info["desc"],
author=info["author"], active=info["active"],
- number=info["n"])
+ number=info["number"])
def load_full_game_from_file(file):
|
AVEgame__AVE-96
|
[
{
"changes": {
"added_entities": [
"ave/__main__.py:make_json"
],
"added_modules": [
"ave/__main__.py:make_json"
],
"edited_entities": [
"ave/__main__.py:run"
],
"edited_modules": [
"ave/__main__.py:run"
]
},
"file": "ave/__main__.py"
},
{
"changes": {
"added_entities": [
"ave/ave.py:AVE.sort_games",
"ave/ave.py:AVE.load_games_from_json"
],
"added_modules": null,
"edited_entities": [
"ave/ave.py:AVE.__init__",
"ave/ave.py:AVE.load_games"
],
"edited_modules": [
"ave/ave.py:AVE"
]
},
"file": "ave/ave.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "ave/config.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"ave/game.py:Game.__init__"
],
"edited_modules": [
"ave/game.py:Game"
]
},
"file": "ave/game.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"ave/game_loader.py:load_game_from_file"
],
"edited_modules": [
"ave/game_loader.py:load_game_from_file"
]
},
"file": "ave/game_loader.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "setup.py"
}
] |
AVEgame/AVE
|
8aad627bf790ca8e452426d7fba5d74ecb75f0a3
|
Create a built in games manifest
We should have a JSON manifest of all built in games constructed before each release. This manifest could then be read to determine the default games on the menu.
A similar strategy could be used for games hosted online. Each time a game is uploaded, it is added to the online manifest (probably in a database rather than a JSON file).
|
diff --git a/.gitignore b/.gitignore
index cd234b2..3e2b7e2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,3 +5,4 @@
build
dist
+gamelist.json
diff --git a/ave/__main__.py b/ave/__main__.py
index 5d8e0ad..971ab74 100644
--- a/ave/__main__.py
+++ b/ave/__main__.py
@@ -1,10 +1,33 @@
"""Functions to run AVE."""
+import os
+import json
from ave import AVE, config
def run():
"""Run AVE in terminal."""
+ from .screen import Screen
+ ave = AVE(screen=Screen())
+ ave.load_games_from_json(os.path.join(config.root_folder, "gamelist.json"))
+ ave.start()
+
+
+def make_json():
+ """Make a json containing metadata for every game."""
+ config.debug = True
ave = AVE()
ave.load_games(config.games_folder)
- ave.start()
+ gamelist = [{
+ "title": game.title,
+ "author": game.author,
+ "desc": game.description,
+ "active": game.active,
+ "version": game.version,
+ "ave_version": game.ave_version,
+ "filename": game.filename,
+ "number": game.number
+ } for game in ave.games]
+
+ with open(os.path.join(config.root_folder, "gamelist.json"), "w") as f:
+ json.dump(gamelist, f)
diff --git a/ave/ave.py b/ave/ave.py
index 9bced08..8daf6b8 100644
--- a/ave/ave.py
+++ b/ave/ave.py
@@ -1,17 +1,19 @@
"""The AVE and GameLibrary classes that run AVE in a terminal."""
import os
+import json
from .exceptions import (AVEGameOver, AVEWinner, AVEToMenu, AVEQuit,
AVENoInternet)
-from .game import Character
+from .game import Game, Character
+from .game_loader import (load_game_from_file, load_library_json,
+ load_game_from_library)
from . import config
-from .screen import Screen
class AVE:
"""The AVE class that runs the Character, Screen and Game."""
- def __init__(self, start_screen=True):
+ def __init__(self, screen=None):
"""Create an AVE class.
Parameters
@@ -19,9 +21,7 @@ class AVE:
start_screen : bool
Should the Screen be started?
"""
- self.screen = None
- if start_screen:
- self.screen = Screen()
+ self.screen = screen
self.character = Character()
self.games = None
self.items = None
@@ -71,6 +71,23 @@ class AVE:
the_game = self.games[game_to_load]
self.run_the_game(the_game)
+ def sort_games(self, games):
+ """Remove disabled games and sort the games by number."""
+ ordered_games = {}
+ other_games = []
+ for g in games:
+ if config.version_tuple < g.ave_version:
+ continue
+ if g.active or config.debug:
+ if g.number is None:
+ other_games.append(g)
+ else:
+ assert g.number not in ordered_games
+ ordered_games[g.number] = g
+ self.games = GameLibrary([
+ ordered_games[i]
+ for i in sorted(ordered_games.keys())] + other_games)
+
def load_games(self, folder):
"""Load the metadata of games from a folder.
@@ -79,23 +96,33 @@ class AVE:
folder: str
The folder
"""
- from .game_loader import load_game_from_file
- ordered_games = {}
- other_games = []
+ games = []
for game in os.listdir(folder):
if game[-4:] == ".ave":
- g = load_game_from_file(os.path.join(folder, game))
- if config.version_tuple < g.ave_version:
- continue
- if g.active or config.debug:
- if g.number is None:
- other_games.append(g)
- else:
- assert g.number not in ordered_games
- ordered_games[g.number] = g
- self.games = GameLibrary([
- ordered_games[i]
- for i in sorted(ordered_games.keys())] + other_games)
+ games.append(load_game_from_file(
+ os.path.join(folder, game), game))
+ self.sort_games(games)
+
+ def load_games_from_json(self, json_file):
+ """Load the metadata of games from a json.
+
+ Parameters
+ ----------
+ json_file: str
+ The location of the json file
+ """
+ with open(json_file) as f:
+ gamelist = json.load(f)
+ games = []
+ for game in gamelist:
+ games.append(Game(
+ file=os.path.join(config.games_folder, game["filename"]),
+ title=game["title"], number=game["number"],
+ description=game["desc"],
+ author=game["author"], active=game["active"],
+ version=game["version"], filename=game["filename"],
+ ave_version=game["ave_version"]))
+ self.sort_games(games)
def get_download_menu(self):
"""Get the list of games from the online library.
@@ -105,7 +132,6 @@ class AVE:
list
A list of the title, author and local url for each game.
"""
- from .game_loader import load_library_json
try:
the_json = load_library_json()
except AVENoInternet:
@@ -120,8 +146,6 @@ class AVE:
def show_download_menu(self):
"""Show a menu of games from the online library."""
- from .game_loader import load_game_from_library
-
try:
self.screen.print_download()
menu_items = self.get_download_menu()
diff --git a/ave/config.py b/ave/config.py
index 5539bd9..3cf36a8 100644
--- a/ave/config.py
+++ b/ave/config.py
@@ -4,14 +4,16 @@ import os
debug = os.getenv("DEBUG")
ave_folder = os.path.dirname(os.path.realpath(__file__))
+root_folder = os.path.join(ave_folder, "..")
+
folder_prefix = ""
-if not os.path.isdir(os.path.join(ave_folder, "../games")):
+if not os.path.isdir(os.path.join(root_folder, "games")):
folder_prefix = "_ave"
-screens_folder = os.path.join(ave_folder, "../" + folder_prefix + "screens")
-games_folder = os.path.join(ave_folder, "../" + folder_prefix + "games")
+screens_folder = os.path.join(root_folder, folder_prefix + "screens")
+games_folder = os.path.join(root_folder, folder_prefix + "games")
-with open(os.path.join(ave_folder, "../VERSION")) as f:
+with open(os.path.join(root_folder, "VERSION")) as f:
version = f.read()
version_tuple = tuple(int(i) for i in version.split("."))
diff --git a/ave/game.py b/ave/game.py
index deeb9cd..22b63c3 100644
--- a/ave/game.py
+++ b/ave/game.py
@@ -121,7 +121,7 @@ class Game:
"""The Game classes that stores all the data to run the game."""
def __init__(self, file=None, url=None,
- title="untitled", number=None,
+ filename=None, title="untitled", number=None,
description="", author="anonymous",
version=0, ave_version=(0, 0),
active=True):
@@ -130,9 +130,11 @@ class Game:
Parameters
----------
file : string
- The filename of the .ave file of this game
+ The full path and filename filename of the .ave file of this game
url : string
The url of the .ave file of this game
+ filename : string
+ The filename of the .ave file of this game
title : string
The title of the game
number : int
@@ -149,6 +151,7 @@ class Game:
If False, this game will only be shown in debug mode
"""
self.file = file
+ self.filename = filename
self.url = url
self.number = number
self.title = title
@@ -156,7 +159,7 @@ class Game:
self.author = author
self.active = active
self.version = version
- self.ave_version = ave_version
+ self.ave_version = tuple(ave_version)
self.rooms = None
self.options = []
diff --git a/ave/game_loader.py b/ave/game_loader.py
index 28b8e72..b7a9c7f 100644
--- a/ave/game_loader.py
+++ b/ave/game_loader.py
@@ -220,7 +220,7 @@ def load_full_game(text):
return rooms, items
-def load_game_from_file(file):
+def load_game_from_file(file, filename=None):
"""Load the metadata of a game from a file."""
title = "untitled"
number = None
@@ -251,9 +251,8 @@ def load_game_from_file(file):
if clean(line[2:-2]) == "off":
active = False
- return Game(file=file, title=title, number=number,
- description=description,
- author=author, active=active,
+ return Game(file=file, filename=filename, title=title, number=number,
+ description=description, author=author, active=active,
version=version, ave_version=ave_version)
diff --git a/setup.py b/setup.py
index 2abf3de..004076f 100644
--- a/setup.py
+++ b/setup.py
@@ -1,6 +1,7 @@
import os
import sys
import setuptools
+from ave.__main__ import make_json
if sys.version_info < (3, 5):
print("Python 3.5 or higher required, please upgrade.")
@@ -9,18 +10,20 @@ if sys.version_info < (3, 5):
with open("VERSION") as f:
VERSION = f.read()
+make_json()
+
requirements = []
if os.name == 'nt':
- # TODO: test this!
requirements.append("windows-curses")
-entry_points = {'console_scripts': ['ave = ave.__main__:run']}
+entry_points = {'console_scripts': ['ave = ave.__main__:run',
+ 'ave-make-json = ave.__main__:make_json']}
data_files = [
("_avegames", [os.path.join("games", i) for i in os.listdir("games")
if i.endswith(".ave")]),
("_avescreens", ["screens/credits", "screens/title", "screens/user"]),
- ("", ["VERSION"])]
+ ("", ["VERSION", "gamelist.json"])]
if __name__ == "__main__":
setuptools.setup(
|
Aarhus-Psychiatry-Research__timeseriesflattener-106
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/timeseriesflattener/feature_spec_objects.py:load_df_with_cache",
"src/timeseriesflattener/feature_spec_objects.py:resolve_from_dict_or_registry"
],
"edited_modules": [
"src/timeseriesflattener/feature_spec_objects.py:load_df_with_cache",
"src/timeseriesflattener/feature_spec_objects.py:resolve_from_dict_or_registry",
"src/timeseriesflattener/feature_spec_objects.py:_MinGroupSpec"
]
},
"file": "src/timeseriesflattener/feature_spec_objects.py"
}
] |
Aarhus-Psychiatry-Research/timeseriesflattener
|
c1a3947a2e1993aa336075856021d009f8a11ad8
|
loader_kwargs in feature_spec_object classes
loader_kwargs not specified as argument in all spec classes
|
diff --git a/src/timeseriesflattener/feature_spec_objects.py b/src/timeseriesflattener/feature_spec_objects.py
index 5315137..5f2682f 100644
--- a/src/timeseriesflattener/feature_spec_objects.py
+++ b/src/timeseriesflattener/feature_spec_objects.py
@@ -23,7 +23,7 @@ log = logging.getLogger(__name__)
@cache
def load_df_with_cache(
loader_fn: Callable,
- kwargs: dict[str, Any],
+ kwargs: Optional[dict[str, Any]],
feature_name: str,
) -> pd.DataFrame:
"""Wrapper function to cache dataframe loading."""
@@ -63,6 +63,8 @@ def resolve_from_dict_or_registry(data: dict[str, Any]):
if callable(data["values_loader"]):
if "loader_kwargs" not in data:
data["loader_kwargs"] = {}
+ elif data["loader_kwargs"] is None:
+ data["loader_kwargs"] = {}
data["values_df"] = load_df_with_cache(
loader_fn=data["values_loader"],
@@ -675,6 +677,11 @@ class _MinGroupSpec(BaseModel):
description="""Prefix for column name, e.g. <prefix>_<feature_name>.""",
)
+ loader_kwargs: Optional[list[dict[str, Any]]] = Field(
+ default=None,
+ description="""Optional kwargs for the values_loader.""",
+ )
+
def _check_loaders_are_valid(self):
"""Check that all loaders can be resolved from the data_loaders catalogue."""
invalid_loaders = list(
@@ -787,8 +794,10 @@ class PredictorGroupSpec(_MinGroupSpec):
resolution, raise an error. Defaults to: [0.0].
prefix (str):
Prefix for column name, e,g, <prefix>_<feature_name>. Defaults to: pred.
+ loader_kwargs (Optional[List[dict[str, Any]]]):
+ Optional kwargs for the values_loader.
lookbehind_days (List[Union[int, float]]):
- How far behind to look for values
+ How far behind to look for values
"""
class Doc:
@@ -815,36 +824,38 @@ class OutcomeGroupSpec(_MinGroupSpec):
"""Specification for a group of outcomes.
Fields:
- values_loader (Optional[List[str]]):
- Loader for the df. Tries to resolve from the data_loaders
- registry, then calls the function which should return a dataframe.
- values_name (Optional[List[str]]):
- List of strings that corresponds to a key in a dictionary
- of multiple dataframes that correspods to a name of a type of values.
- values_df (Optional[DataFrame]):
- Dataframe with the values.
- input_col_name_override (Optional[str]):
- Override for the column name to use as values in df.
- output_col_name_override (Optional[str]):
- Override for the column name to use as values in the
- output df.
- resolve_multiple_fn (List[Union[str, Callable]]):
- Name of resolve multiple fn, resolved from
- resolve_multiple_functions.py
- fallback (List[Union[Callable, str]]):
- Which value to use if no values are found within interval_days.
- allowed_nan_value_prop (List[float]):
- If NaN is higher than this in the input dataframe during
- resolution, raise an error. Defaults to: [0.0].
- prefix (str):
- Prefix for column name, e.g. <prefix>_<feature_name>. Defaults to: outc.
- incident (Sequence[bool]):
- Whether the outcome is incident or not, i.e. whether you
- can experience it more than once. For example, type 2 diabetes is incident.
- Incident outcomes can be handled in a vectorised way during resolution,
- which is faster than non-incident outcomes.
- lookahead_days (List[Union[int, float]]):
- How far ahead to look for values
+ values_loader (Optional[List[str]]):
+ Loader for the df. Tries to resolve from the data_loaders
+ registry, then calls the function which should return a dataframe.
+ values_name (Optional[List[str]]):
+ List of strings that corresponds to a key in a dictionary
+ of multiple dataframes that correspods to a name of a type of values.
+ values_df (Optional[DataFrame]):
+ Dataframe with the values.
+ input_col_name_override (Optional[str]):
+ Override for the column name to use as values in df.
+ output_col_name_override (Optional[str]):
+ Override for the column name to use as values in the
+ output df.
+ resolve_multiple_fn (List[Union[str, Callable]]):
+ Name of resolve multiple fn, resolved from
+ resolve_multiple_functions.py
+ fallback (List[Union[Callable, str]]):
+ Which value to use if no values are found within interval_days.
+ allowed_nan_value_prop (List[float]):
+ If NaN is higher than this in the input dataframe during
+ resolution, raise an error. Defaults to: [0.0].
+ prefix (str):
+ Prefix for column name, e.g. <prefix>_<feature_name>. Defaults to: outc.
+ loader_kwargs (Optional[List[dict[str, Any]]]):
+ Optional kwargs for the values_loader.
+ incident (Sequence[bool]):
+ Whether the outcome is incident or not, i.e. whether you
+ can experience it more than once. For example, type 2 diabetes is incident.
+ Incident outcomes can be handled in a vectorised way during resolution,
+ which is faster than non-incident outcomes.
+ lookahead_days (List[Union[int, float]]):
+ How far ahead to look for values
"""
class Doc:
|
Aarhus-Psychiatry-Research__timeseriesflattener-186
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/timeseriesflattener/feature_spec_objects.py:TemporalSpec.get_col_str"
],
"edited_modules": [
"src/timeseriesflattener/feature_spec_objects.py:TemporalSpec",
"src/timeseriesflattener/feature_spec_objects.py:PredictorSpec",
"src/timeseriesflattener/feature_spec_objects.py:OutcomeSpec",
"src/timeseriesflattener/feature_spec_objects.py:PredictorGroupSpec",
"src/timeseriesflattener/feature_spec_objects.py:OutcomeGroupSpec"
]
},
"file": "src/timeseriesflattener/feature_spec_objects.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"tasks.py:test",
"tasks.py:pr"
],
"edited_modules": [
"tasks.py:test",
"tasks.py:pr"
]
},
"file": "tasks.py"
}
] |
Aarhus-Psychiatry-Research/timeseriesflattener
|
bb6a7fffb2a520272fcb5d7129957ce22484ff77
|
fix: change type hints in specs to allow for floats in interval_days
Currenty, float inputs to interval_days args in predictor and outcome specs are coerced into integers. Thus, it is not possible to generate predictors/outcomes with non-integer lookbehind/ahead windows.
- [ ] Add test
|
diff --git a/.github/workflows/static_type_checks.yml b/.github/workflows/static_type_checks.yml
index abf1bb5..620427d 100644
--- a/.github/workflows/static_type_checks.yml
+++ b/.github/workflows/static_type_checks.yml
@@ -32,7 +32,7 @@ jobs:
uses: actions/setup-python@v4
id: setup_python
with:
- python-version: "3.9"
+ python-version: "3.8"
- name: Install dependencies
shell: bash
diff --git a/pyproject.toml b/pyproject.toml
index 50efc2b..38bd66d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -194,6 +194,7 @@ commands =
[testenv:type]
description: run static type checking
extras = test, text, dev
+basepython = py38
use_develop = true
allowlist_externals = ls
commands =
diff --git a/src/timeseriesflattener/feature_spec_objects.py b/src/timeseriesflattener/feature_spec_objects.py
index bedcc13..eac7535 100644
--- a/src/timeseriesflattener/feature_spec_objects.py
+++ b/src/timeseriesflattener/feature_spec_objects.py
@@ -356,7 +356,7 @@ class TemporalSpec(_AnySpec):
or timestamp_col_name.
output_col_name_override (Optional[str]):
Override the generated column name after flattening the time series
- interval_days (Union[int, float, NoneType]):
+ interval_days (Optional[float]):
How far to look in the given direction (ahead for outcomes,
behind for predictors)
resolve_multiple_fn (Union[Callable, str]):
@@ -381,7 +381,7 @@ class TemporalSpec(_AnySpec):
short_description = """The minimum specification required for collapsing a temporal
feature, whether looking ahead or behind. Mostly used for inheritance below."""
- interval_days: Optional[Union[int, float]] = Field(
+ interval_days: Optional[float] = Field(
description="""How far to look in the given direction (ahead for outcomes,
behind for predictors)""",
)
@@ -444,6 +444,7 @@ class TemporalSpec(_AnySpec):
def get_col_str(self, additional_feature_name: Optional[str] = None) -> str:
"""Generate the column name for the output column.
+ If interval days is a float, the decimal point is changed to an underscore.
Args:
additional_feature_name (Optional[str]): additional feature name to
@@ -452,7 +453,14 @@ class TemporalSpec(_AnySpec):
feature_name = self.feature_name
if additional_feature_name:
feature_name = feature_name + "-" + str(additional_feature_name)
- col_str = f"{self.prefix}_{feature_name}_within_{self.interval_days}_days_{self.key_for_resolve_multiple}_fallback_{self.fallback}"
+
+ interval_days_str = ( # This is required because pydantic coerces the int 2 to float 2.0
+ int(self.interval_days) # type: ignore
+ if self.interval_days.is_integer() # type: ignore
+ else str(self.interval_days).replace(".", "-")
+ )
+
+ col_str = f"{self.prefix}_{feature_name}_within_{interval_days_str}_days_{self.key_for_resolve_multiple}_fallback_{self.fallback}"
return col_str
@@ -483,7 +491,7 @@ class PredictorSpec(TemporalSpec):
or timestamp_col_name.
output_col_name_override (Optional[str]):
Override the generated column name after flattening the time series
- interval_days (Union[int, float, NoneType]):
+ interval_days (Optional[float]):
How far to look in the given direction (ahead for outcomes,
behind for predictors)
resolve_multiple_fn (Union[Callable, str]):
@@ -502,7 +510,7 @@ class PredictorSpec(TemporalSpec):
resolution, raise an error. Defaults to: 0.0.
entity_id_col_name (str):
Col name for ids in the input dataframe. Defaults to: entity_id.
- lookbehind_days (Union[int, float]):
+ lookbehind_days (float):
How far behind to look for values
"""
@@ -517,7 +525,7 @@ class PredictorSpec(TemporalSpec):
<prefix>_<feature_name>.""",
)
- lookbehind_days: Union[int, float] = Field(
+ lookbehind_days: float = Field(
description="""How far behind to look for values""",
)
@@ -561,7 +569,7 @@ class TextPredictorSpec(PredictorSpec):
or timestamp_col_name.
output_col_name_override (Optional[str]):
Override the generated column name after flattening the time series
- interval_days (Union[int, float, NoneType]):
+ interval_days (Optional[float]):
How far to look in the given direction (ahead for outcomes,
behind for predictors)
resolve_multiple_fn (Union[Callable, str]):
@@ -582,7 +590,7 @@ class TextPredictorSpec(PredictorSpec):
resolution, raise an error. Defaults to: 0.0.
entity_id_col_name (str):
Col name for ids in the input dataframe. Defaults to: entity_id.
- lookbehind_days (Union[int, float]):
+ lookbehind_days (float):
How far behind to look for values
embedding_fn (Callable):
A function used for embedding the text. Should take a
@@ -653,7 +661,7 @@ class OutcomeSpec(TemporalSpec):
or timestamp_col_name.
output_col_name_override (Optional[str]):
Override the generated column name after flattening the time series
- interval_days (Union[int, float, NoneType]):
+ interval_days (Optional[float]):
How far to look in the given direction (ahead for outcomes,
behind for predictors)
resolve_multiple_fn (Union[Callable, str]):
@@ -677,7 +685,7 @@ class OutcomeSpec(TemporalSpec):
I.e., incident outcomes are outcomes you can only experience once.
For example, type 2 diabetes is incident. Incident outcomes can be handled
in a vectorised way during resolution, which is faster than non-incident outcomes.
- lookahead_days (Union[int, float]):
+ lookahead_days (float):
How far ahead to look for values
"""
@@ -699,7 +707,7 @@ class OutcomeSpec(TemporalSpec):
in a vectorised way during resolution, which is faster than non-incident outcomes.""",
)
- lookahead_days: Union[int, float] = Field(
+ lookahead_days: float = Field(
description="""How far ahead to look for values""",
)
@@ -903,7 +911,7 @@ class PredictorGroupSpec(_MinGroupSpec):
Prefix for column name, e,g, <prefix>_<feature_name>. Defaults to: pred.
loader_kwargs (Optional[List[Dict[str, Any]]]):
Optional kwargs for the values_loader.
- lookbehind_days (List[Union[int, float]]):
+ lookbehind_days (List[float]):
How far behind to look for values
"""
@@ -915,7 +923,7 @@ class PredictorGroupSpec(_MinGroupSpec):
description="""Prefix for column name, e,g, <prefix>_<feature_name>.""",
)
- lookbehind_days: List[Union[int, float]] = Field(
+ lookbehind_days: List[float] = Field(
description="""How far behind to look for values""",
)
@@ -961,7 +969,7 @@ class OutcomeGroupSpec(_MinGroupSpec):
can experience it more than once. For example, type 2 diabetes is incident.
Incident outcomes can be handled in a vectorised way during resolution,
which is faster than non-incident outcomes.
- lookahead_days (List[Union[int, float]]):
+ lookahead_days (List[float]):
How far ahead to look for values
"""
@@ -980,7 +988,7 @@ class OutcomeGroupSpec(_MinGroupSpec):
which is faster than non-incident outcomes.""",
)
- lookahead_days: List[Union[int, float]] = Field(
+ lookahead_days: List[float] = Field(
description="""How far ahead to look for values""",
)
diff --git a/tasks.py b/tasks.py
index 5cab18b..b9965f4 100644
--- a/tasks.py
+++ b/tasks.py
@@ -20,7 +20,7 @@ import platform
import re
from dataclasses import dataclass
from pathlib import Path
-from typing import Optional
+from typing import List, Optional
from invoke import Context, Result, task
@@ -236,24 +236,36 @@ def update(c: Context):
c.run("pip install --upgrade -e '.[dev,tests,docs]'")
-@task
-def test(c: Context, run_all_envs: bool = False):
+@task(iterable="pytest_args")
+def test(
+ c: Context,
+ python_versions: str = "3.9",
+ pytest_args: List[str] = [], # noqa
+):
"""Run tests"""
echo_header(f"{Emo.TEST} Running tests")
- pytest_args = "-n auto -rfE --failed-first -p no:cov --disable-warnings -q"
- if not run_all_envs:
- test_result: Result = c.run(
- f"tox -e py311 -- {pytest_args}",
- warn=True,
- pty=True,
- )
- else:
- test_result = c.run(
- f"tox -- {pytest_args}",
- warn=True,
- pty=True,
- )
+ if len(pytest_args) == 0:
+ pytest_args = [
+ "-n auto",
+ "-rfE",
+ "--failed-first",
+ "-p no:cov",
+ "--disable-warnings",
+ "-q",
+ ]
+
+ pytest_arg_str = " ".join(pytest_args)
+
+ python_version_list = python_versions.replace(".", "").split(",")
+ python_version_strings = [f"py{v}" for v in python_version_list]
+ python_version_arg_string = ",".join(python_version_strings)
+
+ test_result: Result = c.run(
+ f"tox -e {python_version_arg_string} -- {pytest_arg_str}",
+ warn=True,
+ pty=True,
+ )
# If "failed" in the pytest results
if "failed" in test_result.stdout:
@@ -302,7 +314,7 @@ def pr(c: Context, auto_fix: bool = False):
"""Run all checks and update the PR."""
add_and_commit(c)
lint(c, auto_fix=auto_fix)
- test(c, run_all_envs=True)
+ test(c, python_versions="3.8,3.11")
update_branch(c)
update_pr(c)
|
Aarhus-Psychiatry-Research__timeseriesflattener-33
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "src/timeseriesflattener/__init__.py"
},
{
"changes": {
"added_entities": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.__init__",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._load_cached_df_and_expand_fallback",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._flatten_temporal_values_to_df",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._generate_values_for_cache_checking",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._get_temporal_feature",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._concatenate_flattened_timeseries",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_age_and_birth_year",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_static_info",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._add_incident_outcome",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_temporal_col_to_flattened_dataset",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.get_df"
],
"added_modules": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener"
],
"edited_entities": [
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset.__init__",
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset._load_cached_df_and_expand_fallback",
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset._flatten_temporal_values_to_df",
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset._generate_values_for_cache_checking",
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset._get_temporal_feature",
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset._concatenate_flattened_timeseries",
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset.add_age_and_birth_year",
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset.add_static_info",
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset._add_incident_outcome",
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset.add_temporal_col_to_flattened_dataset"
],
"edited_modules": [
"src/timeseriesflattener/flattened_dataset.py:FlattenedDataset"
]
},
"file": "src/timeseriesflattener/flattened_dataset.py"
}
] |
Aarhus-Psychiatry-Research/timeseriesflattener
|
0b6895a23bd620615b06e442d0887bc73f345540
|
Refactor: Main class TSFLattener, add df_getter method
|
diff --git a/src/timeseriesflattener/__init__.py b/src/timeseriesflattener/__init__.py
index c4eae1f..1516176 100644
--- a/src/timeseriesflattener/__init__.py
+++ b/src/timeseriesflattener/__init__.py
@@ -1,2 +1,2 @@
"""Init timeseriesflattener."""
-from .flattened_dataset import FlattenedDataset
+from .flattened_dataset import TimeseriesFlattener
diff --git a/src/timeseriesflattener/flattened_dataset.py b/src/timeseriesflattener/flattened_dataset.py
index 165a39e..cc200ac 100644
--- a/src/timeseriesflattener/flattened_dataset.py
+++ b/src/timeseriesflattener/flattened_dataset.py
@@ -31,7 +31,7 @@ from timeseriesflattener.utils import load_dataset_from_file, write_df_to_file
ProgressBar().register()
-class FlattenedDataset: # pylint: disable=too-many-instance-attributes
+class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
"""Turn a set of time-series into tabular prediction-time data.
Attributes:
@@ -111,18 +111,18 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
if "value" in prediction_times_df.columns:
prediction_times_df.drop("value", axis=1, inplace=True)
- self.df = prediction_times_df
+ self._df = prediction_times_df
ValidateInitFlattenedDataset(
- df=self.df,
+ df=self._df,
timestamp_col_name=self.timestamp_col_name,
id_col_name=self.id_col_name,
).validate_dataset()
# Create pred_time_uuid_columne
- self.df[self.pred_time_uuid_col_name] = self.df[self.id_col_name].astype(
+ self._df[self.pred_time_uuid_col_name] = self._df[self.id_col_name].astype(
str,
- ) + self.df[self.timestamp_col_name].dt.strftime("-%Y-%m-%d-%H-%M-%S")
+ ) + self._df[self.timestamp_col_name].dt.strftime("-%Y-%m-%d-%H-%M-%S")
def _load_most_recent_df_matching_pattern(
self,
@@ -179,7 +179,7 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
# Expand fallback column
df = pd.merge(
- left=self.df[self.pred_time_uuid_col_name],
+ left=self._df[self.pred_time_uuid_col_name],
right=df,
how="left",
on=self.pred_time_uuid_col_name,
@@ -245,7 +245,7 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
else:
raise ValueError(f"Unknown output_spec type {type(output_spec)}")
- df = FlattenedDataset._drop_records_outside_interval_days(
+ df = TimeseriesFlattener._drop_records_outside_interval_days(
df,
direction=direction,
interval_days=output_spec.interval_days,
@@ -254,7 +254,7 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
)
# Add back prediction times that don't have a value, and fill them with fallback
- df = FlattenedDataset._add_back_prediction_times_without_value(
+ df = TimeseriesFlattener._add_back_prediction_times_without_value(
df=df,
pred_times_with_uuid=prediction_times_with_uuid_df,
pred_time_uuid_colname=pred_time_uuid_col_name,
@@ -262,7 +262,7 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
df["timestamp_val"].replace({output_spec.fallback: pd.NaT}, inplace=True)
- df = FlattenedDataset._resolve_multiple_values_within_interval_days(
+ df = TimeseriesFlattener._resolve_multiple_values_within_interval_days(
resolve_multiple=output_spec.resolve_multiple_fn,
df=df,
pred_time_uuid_colname=pred_time_uuid_col_name,
@@ -308,10 +308,10 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
f"{value_col_str[20]}, {n_trials}: Generated_df was all fallback values, regenerating",
)
- n_to_generate = int(min(n_to_generate, len(self.df)))
+ n_to_generate = int(min(n_to_generate, len(self._df)))
generated_df = self._flatten_temporal_values_to_df(
- prediction_times_with_uuid_df=self.df.sample(
+ prediction_times_with_uuid_df=self._df.sample(
n=n_to_generate,
replace=False,
),
@@ -470,7 +470,7 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
msg.info("No cache dir specified, not attempting load")
df = self._flatten_temporal_values_to_df(
- prediction_times_with_uuid_df=self.df[
+ prediction_times_with_uuid_df=self._df[
[
self.pred_time_uuid_col_name,
self.id_col_name,
@@ -553,7 +553,7 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
msg.info(f"Concatenation took {round(end_time - start_time, 3)} seconds")
msg.info("Merging with original df")
- self.df = self.df.merge(right=new_features, on=self.pred_time_uuid_col_name)
+ self._df = self._df.merge(right=new_features, on=self.pred_time_uuid_col_name)
def add_temporal_predictors_from_pred_specs( # pylint: disable=too-many-branches
self,
@@ -621,14 +621,16 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
data_of_birth_col_name = f"{output_prefix}_{input_date_of_birth_col_name}"
- self.df[output_age_col_name] = (
- (self.df[self.timestamp_col_name] - self.df[data_of_birth_col_name]).dt.days
+ self._df[output_age_col_name] = (
+ (
+ self._df[self.timestamp_col_name] - self._df[data_of_birth_col_name]
+ ).dt.days
/ (365.25)
).round(2)
if birth_year_as_predictor:
# Convert datetime to year
- self.df["pred_birth_year"] = self.df[data_of_birth_col_name].dt.year
+ self._df["pred_birth_year"] = self._df[data_of_birth_col_name].dt.year
def add_static_info(
self,
@@ -676,8 +678,8 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
},
)
- self.df = pd.merge(
- self.df,
+ self._df = pd.merge(
+ self._df,
df,
how="left",
on=self.id_col_name,
@@ -697,7 +699,7 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
outcome_timestamp_col_name = f"{self.timestamp_col_name}_outcome"
df = pd.merge(
- self.df,
+ self._df,
outcome_spec.values_df,
how="left",
on=self.id_col_name,
@@ -727,7 +729,7 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
df.drop(["value"], axis=1, inplace=True)
- self.df = df
+ self._df = df
def add_temporal_outcome(
self,
@@ -781,8 +783,8 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
f"{self.timestamp_col_name} is of type {timestamp_col_type}, not 'Timestamp' from Pandas. Will cause problems. Convert before initialising FlattenedDataset.",
)
- df = FlattenedDataset._flatten_temporal_values_to_df(
- prediction_times_with_uuid_df=self.df[
+ df = TimeseriesFlattener._flatten_temporal_values_to_df(
+ prediction_times_with_uuid_df=self._df[
[
self.id_col_name,
self.timestamp_col_name,
@@ -795,7 +797,7 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
pred_time_uuid_col_name=self.pred_time_uuid_col_name,
)
- self.df = self.df.merge(
+ self._df = self._df.merge(
right=df,
on=self.pred_time_uuid_col_name,
validate="1:1",
@@ -911,3 +913,11 @@ class FlattenedDataset: # pylint: disable=too-many-instance-attributes
["is_in_interval", "time_from_pred_to_val_in_days"],
axis=1,
)
+
+ def get_df(self) -> DataFrame:
+ """Get the flattened dataframe.
+
+ Returns:
+ DataFrame: Flattened dataframe.
+ """
+ return self._df
|
Aarhus-Psychiatry-Research__timeseriesflattener-337
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"src/timeseriesflattener/feature_specs/group_specs.py:PredictorGroupSpec",
"src/timeseriesflattener/feature_specs/group_specs.py:OutcomeGroupSpec"
]
},
"file": "src/timeseriesflattener/feature_specs/group_specs.py"
},
{
"changes": {
"added_entities": [
"src/timeseriesflattener/feature_specs/single_specs.py:LookPeriod.__post_init__",
"src/timeseriesflattener/feature_specs/single_specs.py:OutcomeSpec.lookahead_period",
"src/timeseriesflattener/feature_specs/single_specs.py:PredictorSpec.lookbehind_period"
],
"added_modules": [
"src/timeseriesflattener/feature_specs/single_specs.py:LookPeriod"
],
"edited_entities": [
"src/timeseriesflattener/feature_specs/single_specs.py:coerce_floats",
"src/timeseriesflattener/feature_specs/single_specs.py:get_temporal_col_name",
"src/timeseriesflattener/feature_specs/single_specs.py:OutcomeSpec.get_output_col_name",
"src/timeseriesflattener/feature_specs/single_specs.py:PredictorSpec.get_output_col_name"
],
"edited_modules": [
"src/timeseriesflattener/feature_specs/single_specs.py:CoercedFloats",
"src/timeseriesflattener/feature_specs/single_specs.py:coerce_floats",
"src/timeseriesflattener/feature_specs/single_specs.py:get_temporal_col_name",
"src/timeseriesflattener/feature_specs/single_specs.py:OutcomeSpec",
"src/timeseriesflattener/feature_specs/single_specs.py:PredictorSpec"
]
},
"file": "src/timeseriesflattener/feature_specs/single_specs.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._drop_records_outside_interval_days",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._flatten_temporal_values_to_df",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._add_incident_outcome",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._get_cutoff_date_from_spec"
],
"edited_modules": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener"
]
},
"file": "src/timeseriesflattener/flattened_dataset.py"
}
] |
Aarhus-Psychiatry-Research/timeseriesflattener
|
0f21608e4c3743545c6aadb844493c47e895fc20
|
feat: add option to specify time range in predictions
Creating features in bins of e.g. 0-7, 7-30, 30-90, 90-365, 365-... days from prediction time instead of always going from 0-n as we do now, could potentially keep more temporal information and create better predictors.
|
diff --git a/docs/tutorials/01_basic.ipynb b/docs/tutorials/01_basic.ipynb
index 9bdd35d..a354fae 100644
--- a/docs/tutorials/01_basic.ipynb
+++ b/docs/tutorials/01_basic.ipynb
@@ -52,6 +52,15 @@
"execution_count": 1,
"metadata": {},
"outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "/Users/au554730/Desktop/Projects/timeseriesflattener/.venv/lib/python3.10/site-packages/pydantic/_internal/_config.py:269: UserWarning: Valid config keys have changed in V2:\n",
+ "* 'allow_mutation' has been removed\n",
+ " warnings.warn(message, UserWarning)\n"
+ ]
+ },
{
"data": {
"text/html": [
@@ -877,7 +886,7 @@
},
{
"cell_type": "code",
- "execution_count": 11,
+ "execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
@@ -908,6 +917,8 @@
"\n",
"We also specify that the outcome is not incident. This means that patient ID (dw_ek_borger) can experience the outcome more than once. If the outcome was marked as incident, all prediction times after the patient experiences the outcome are dropped. This is useful for cases where an event is permanent - for example, whether a patient has type 1 diabetes or not.\n",
"\n",
+ "Here, we specifiy that we want to look 365 days forward from the prediction time to search for outcomes. If we wanted to require a certain period of time from the prediction time before we look for outcome values, we can specify `lookahead_days` as an interval of (min_days, max_days) as a tuple instead. \n",
+ "\n",
"Lastly, we specify a name of the outcome which'll be used when generating its column."
]
},
@@ -956,6 +967,30 @@
"Values within the *lookbehind* window are aggregated using `aggregation_fn`, for example the mean as shown in this example, or max/min etc. "
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Temporal predictors can also be specified to look for values within a certain time range from the prediction time, similar to outcome specifications. For instance, you might want to create multiple predictors, where one looks for values within (0, 30) days, and another within (31, 182) days. \n",
+ "\n",
+ "This can easily be specified by passing a tuple[min_days, max_days] to the lookbehind_days parameter."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "temporal_interval_predictor_spec = PredictorSpec(\n",
+ " timeseries_df=df_synth_predictors,\n",
+ " lookbehind_days=(30, 90),\n",
+ " fallback=np.nan,\n",
+ " aggregation_fn=mean,\n",
+ " feature_base_name=\"predictor_interval_name\",\n",
+ ")"
+ ]
+ },
{
"attachments": {},
"cell_type": "markdown",
@@ -1146,30 +1181,33 @@
},
{
"cell_type": "code",
- "execution_count": 12,
+ "execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
- "ts_flattener.add_spec([sex_predictor_spec, temporal_predictor_spec, outcome_spec])"
+ "ts_flattener.add_spec([sex_predictor_spec, temporal_predictor_spec, temporal_interval_predictor_spec, outcome_spec])"
]
},
{
"cell_type": "code",
- "execution_count": 13,
+ "execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
- "2023-06-14 16:11:40 [INFO] There were unprocessed specs, computing...\n",
- "2023-06-14 16:11:40 [INFO] _drop_pred_time_if_insufficient_look_distance: Dropped 5999 (59.99%) rows\n",
- "2023-06-14 16:11:40 [INFO] Processing 2 temporal features in parallel with 1 workers. Chunksize is 2. If this is above 1, it may take some time for the progress bar to move, as processing is batched. However, this makes for much faster total performance.\n",
- "100%|██████████| 2/2 [00:00<00:00, 2.14it/s]\n",
- "2023-06-14 16:11:41 [INFO] Checking alignment of dataframes - this might take a little while (~2 minutes for 1.000 dataframes with 2.000.000 rows).\n",
- "2023-06-14 16:11:41 [INFO] Starting concatenation. Will take some time on performant systems, e.g. 30s for 100 features and 2_000_000 prediction times. This is normal.\n",
- "2023-06-14 16:11:41 [INFO] Concatenation took 0.003 seconds\n",
- "2023-06-14 16:11:41 [INFO] Merging with original df\n"
+ "2024-01-18 11:34:22 [INFO] There were unprocessed specs, computing...\n",
+ "2024-01-18 11:34:22 [INFO] _drop_pred_time_if_insufficient_look_distance: Dropped 5999 (59.99%) rows\n",
+ "2024-01-18 11:34:22 [INFO] Processing 3 temporal features in parallel with 1 workers. Chunksize is 3. If this is above 1, it may take some time for the progress bar to move, as processing is batched. However, this makes for much faster total performance.\n",
+ " 0%| | 0/3 [00:00<?, ?it/s]/Users/au554730/Desktop/Projects/timeseriesflattener/.venv/lib/python3.10/site-packages/pydantic/_internal/_config.py:269: UserWarning: Valid config keys have changed in V2:\n",
+ "* 'allow_mutation' has been removed\n",
+ " warnings.warn(message, UserWarning)\n",
+ "100%|██████████| 3/3 [00:01<00:00, 2.11it/s]\n",
+ "2024-01-18 11:34:24 [INFO] Checking alignment of dataframes - this might take a little while (~2 minutes for 1.000 dataframes with 2.000.000 rows).\n",
+ "2024-01-18 11:34:24 [INFO] Starting concatenation. Will take some time on performant systems, e.g. 30s for 100 features and 2_000_000 prediction times. This is normal.\n",
+ "2024-01-18 11:34:24 [INFO] Concatenation took 0.005 seconds\n",
+ "2024-01-18 11:34:24 [INFO] Merging with original df\n"
]
},
{
@@ -1180,20 +1218,21 @@
"│ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ │\n",
"│ ┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> dataframe </span>┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Values </span>┃ ┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Column Type </span>┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Count </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ │\n",
- "│ │ Number of rows │ 4001 │ │ int64 │ 2 │ │\n",
- "│ │ Number of columns │ 6 │ │ float64 │ 2 │ │\n",
+ "│ │ Number of rows │ 4001 │ │ float64 │ 3 │ │\n",
+ "│ │ Number of columns │ 7 │ │ int64 │ 2 │ │\n",
"│ └───────────────────┴────────┘ │ datetime64 │ 1 │ │\n",
"│ │ string │ 1 │ │\n",
"│ └─────────────┴───────┘ │\n",
"│ <span style=\"font-style: italic\"> number </span> │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
- "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">entity_id </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2600</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█████▇ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_predictor_name_ </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 72</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.097</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.9</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.9</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▃██▃▁ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">outc_outcome_name_wi </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.064</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.25</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█ ▁ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_female </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.49</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█ █ </span> │ │\n",
- "│ └────────────────────────────┴─────┴────────┴─────────┴────────┴─────────┴────────┴───────┴────────┴─────────┘ │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┓ │\n",
+ "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━┩ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">entity_id </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2600</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█████▇</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_predictor_name_ </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 72</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.097</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.9</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.9</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▃██▃▁</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_predictor_inter </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 72</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.02</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7.4</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▇▇▇██▇</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">outc_outcome_name_wi </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.064</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.25</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█ ▁</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_female </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.49</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█ █</span> │ │\n",
+ "│ └───────────────────────────┴────────┴────────┴─────────┴────────┴─────────┴───────┴───────┴────────┴────────┘ │\n",
"│ <span style=\"font-style: italic\"> datetime </span> │\n",
"│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
"│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> first </span>┃<span style=\"font-weight: bold\"> last </span>┃<span style=\"font-weight: bold\"> frequency </span>┃ │\n",
@@ -1215,20 +1254,21 @@
"│ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ │\n",
"│ ┃\u001b[1;36m \u001b[0m\u001b[1;36mdataframe \u001b[0m\u001b[1;36m \u001b[0m┃\u001b[1;36m \u001b[0m\u001b[1;36mValues\u001b[0m\u001b[1;36m \u001b[0m┃ ┃\u001b[1;36m \u001b[0m\u001b[1;36mColumn Type\u001b[0m\u001b[1;36m \u001b[0m┃\u001b[1;36m \u001b[0m\u001b[1;36mCount\u001b[0m\u001b[1;36m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ │\n",
- "│ │ Number of rows │ 4001 │ │ int64 │ 2 │ │\n",
- "│ │ Number of columns │ 6 │ │ float64 │ 2 │ │\n",
+ "│ │ Number of rows │ 4001 │ │ float64 │ 3 │ │\n",
+ "│ │ Number of columns │ 7 │ │ int64 │ 2 │ │\n",
"│ └───────────────────┴────────┘ │ datetime64 │ 1 │ │\n",
"│ │ string │ 1 │ │\n",
"│ └─────────────┴───────┘ │\n",
"│ \u001b[3m number \u001b[0m │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
- "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mentity_id \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 3\u001b[0m │ \u001b[36m 2600\u001b[0m │ \u001b[36m 7500\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m█████▇ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_predictor_name_ \u001b[0m │ \u001b[36m 72\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 1.6\u001b[0m │ \u001b[36m 0.097\u001b[0m │ \u001b[36m 3.9\u001b[0m │ \u001b[36m 6\u001b[0m │ \u001b[36m 9.9\u001b[0m │ \u001b[32m▁▃██▃▁ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141moutc_outcome_name_wi \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.064\u001b[0m │ \u001b[36m 0.25\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m█ ▁ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_female \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.49\u001b[0m │ \u001b[36m 0.5\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m█ █ \u001b[0m │ │\n",
- "│ └────────────────────────────┴─────┴────────┴─────────┴────────┴─────────┴────────┴───────┴────────┴─────────┘ │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┓ │\n",
+ "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━┩ │\n",
+ "│ │ \u001b[38;5;141mentity_id \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 3\u001b[0m │ \u001b[36m 2600\u001b[0m │ \u001b[36m 7500\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m█████▇\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_predictor_name_ \u001b[0m │ \u001b[36m 72\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 1.6\u001b[0m │ \u001b[36m 0.097\u001b[0m │ \u001b[36m 3.9\u001b[0m │ \u001b[36m 6\u001b[0m │ \u001b[36m 9.9\u001b[0m │ \u001b[32m▁▃██▃▁\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_predictor_inter \u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 72\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 2.8\u001b[0m │ \u001b[36m 0.02\u001b[0m │ \u001b[36m 2.6\u001b[0m │ \u001b[36m 7.4\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m▇▇▇██▇\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141moutc_outcome_name_wi \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.064\u001b[0m │ \u001b[36m 0.25\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m█ ▁\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_female \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.49\u001b[0m │ \u001b[36m 0.5\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m█ █\u001b[0m │ │\n",
+ "│ └───────────────────────────┴────────┴────────┴─────────┴────────┴─────────┴───────┴───────┴────────┴────────┘ │\n",
"│ \u001b[3m datetime \u001b[0m │\n",
"│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
"│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mfirst \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mlast \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mfrequency \u001b[0m\u001b[1m \u001b[0m┃ │\n",
@@ -1253,12 +1293,13 @@
"['entity_id',\n",
" 'timestamp',\n",
" 'prediction_time_uuid',\n",
- " 'pred_predictor_name_within_730_days_mean_fallback_nan',\n",
- " 'outc_outcome_name_within_365_days_maximum_fallback_0_dichotomous',\n",
+ " 'pred_predictor_name_within_0_to_730_days_mean_fallback_nan',\n",
+ " 'pred_predictor_interval_name_within_30_to_90_days_mean_fallback_nan',\n",
+ " 'outc_outcome_name_within_0_to_365_days_maximum_fallback_0_dichotomous',\n",
" 'pred_female']"
]
},
- "execution_count": 13,
+ "execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
@@ -1273,7 +1314,7 @@
},
{
"cell_type": "code",
- "execution_count": 14,
+ "execution_count": 12,
"metadata": {},
"outputs": [
{
@@ -1281,117 +1322,128 @@
"text/html": [
"<style type=\"text/css\">\n",
"</style>\n",
- "<table id=\"T_003c4\" style=\"font-size: 14px\">\n",
+ "<table id=\"T_4dbad\" style=\"font-size: 14px\">\n",
" <thead>\n",
" <tr>\n",
" <th class=\"blank level0\" > </th>\n",
- " <th id=\"T_003c4_level0_col0\" class=\"col_heading level0 col0\" >entity_id</th>\n",
- " <th id=\"T_003c4_level0_col1\" class=\"col_heading level0 col1\" >timestamp</th>\n",
- " <th id=\"T_003c4_level0_col2\" class=\"col_heading level0 col2\" >prediction_time_uuid</th>\n",
- " <th id=\"T_003c4_level0_col3\" class=\"col_heading level0 col3\" >pred_X</th>\n",
- " <th id=\"T_003c4_level0_col4\" class=\"col_heading level0 col4\" >outc_Y</th>\n",
- " <th id=\"T_003c4_level0_col5\" class=\"col_heading level0 col5\" >pred_female</th>\n",
+ " <th id=\"T_4dbad_level0_col0\" class=\"col_heading level0 col0\" >entity_id</th>\n",
+ " <th id=\"T_4dbad_level0_col1\" class=\"col_heading level0 col1\" >timestamp</th>\n",
+ " <th id=\"T_4dbad_level0_col2\" class=\"col_heading level0 col2\" >prediction_time_uuid</th>\n",
+ " <th id=\"T_4dbad_level0_col3\" class=\"col_heading level0 col3\" >pred_X</th>\n",
+ " <th id=\"T_4dbad_level0_col4\" class=\"col_heading level0 col4\" >pred_X_30_to_90</th>\n",
+ " <th id=\"T_4dbad_level0_col5\" class=\"col_heading level0 col5\" >outc_Y</th>\n",
+ " <th id=\"T_4dbad_level0_col6\" class=\"col_heading level0 col6\" >pred_female</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
- " <th id=\"T_003c4_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
- " <td id=\"T_003c4_row0_col0\" class=\"data row0 col0\" >9903</td>\n",
- " <td id=\"T_003c4_row0_col1\" class=\"data row0 col1\" >1968-05-09 21:24:00</td>\n",
- " <td id=\"T_003c4_row0_col2\" class=\"data row0 col2\" >9903-1968-05-09-21-24-00</td>\n",
- " <td id=\"T_003c4_row0_col3\" class=\"data row0 col3\" >0.990763</td>\n",
- " <td id=\"T_003c4_row0_col4\" class=\"data row0 col4\" >0.000000</td>\n",
- " <td id=\"T_003c4_row0_col5\" class=\"data row0 col5\" >0</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th id=\"T_003c4_level0_row1\" class=\"row_heading level0 row1\" >1</th>\n",
- " <td id=\"T_003c4_row1_col0\" class=\"data row1 col0\" >6447</td>\n",
- " <td id=\"T_003c4_row1_col1\" class=\"data row1 col1\" >1967-09-25 18:08:00</td>\n",
- " <td id=\"T_003c4_row1_col2\" class=\"data row1 col2\" >6447-1967-09-25-18-08-00</td>\n",
- " <td id=\"T_003c4_row1_col3\" class=\"data row1 col3\" >5.582745</td>\n",
- " <td id=\"T_003c4_row1_col4\" class=\"data row1 col4\" >0.000000</td>\n",
- " <td id=\"T_003c4_row1_col5\" class=\"data row1 col5\" >1</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th id=\"T_003c4_level0_row2\" class=\"row_heading level0 row2\" >2</th>\n",
- " <td id=\"T_003c4_row2_col0\" class=\"data row2 col0\" >4927</td>\n",
- " <td id=\"T_003c4_row2_col1\" class=\"data row2 col1\" >1968-06-30 12:13:00</td>\n",
- " <td id=\"T_003c4_row2_col2\" class=\"data row2 col2\" >4927-1968-06-30-12-13-00</td>\n",
- " <td id=\"T_003c4_row2_col3\" class=\"data row2 col3\" >4.957251</td>\n",
- " <td id=\"T_003c4_row2_col4\" class=\"data row2 col4\" >0.000000</td>\n",
- " <td id=\"T_003c4_row2_col5\" class=\"data row2 col5\" >0</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th id=\"T_003c4_level0_row3\" class=\"row_heading level0 row3\" >3</th>\n",
- " <td id=\"T_003c4_row3_col0\" class=\"data row3 col0\" >5475</td>\n",
- " <td id=\"T_003c4_row3_col1\" class=\"data row3 col1\" >1967-01-09 03:09:00</td>\n",
- " <td id=\"T_003c4_row3_col2\" class=\"data row3 col2\" >5475-1967-01-09-03-09-00</td>\n",
- " <td id=\"T_003c4_row3_col3\" class=\"data row3 col3\" >5.999336</td>\n",
- " <td id=\"T_003c4_row3_col4\" class=\"data row3 col4\" >0.000000</td>\n",
- " <td id=\"T_003c4_row3_col5\" class=\"data row3 col5\" >0</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th id=\"T_003c4_level0_row4\" class=\"row_heading level0 row4\" >4</th>\n",
- " <td id=\"T_003c4_row4_col0\" class=\"data row4 col0\" >9793</td>\n",
- " <td id=\"T_003c4_row4_col1\" class=\"data row4 col1\" >1968-12-15 12:59:00</td>\n",
- " <td id=\"T_003c4_row4_col2\" class=\"data row4 col2\" >9793-1968-12-15-12-59-00</td>\n",
- " <td id=\"T_003c4_row4_col3\" class=\"data row4 col3\" >7.294038</td>\n",
- " <td id=\"T_003c4_row4_col4\" class=\"data row4 col4\" >0.000000</td>\n",
- " <td id=\"T_003c4_row4_col5\" class=\"data row4 col5\" >0</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th id=\"T_003c4_level0_row5\" class=\"row_heading level0 row5\" >5</th>\n",
- " <td id=\"T_003c4_row5_col0\" class=\"data row5 col0\" >9768</td>\n",
- " <td id=\"T_003c4_row5_col1\" class=\"data row5 col1\" >1967-07-04 23:09:00</td>\n",
- " <td id=\"T_003c4_row5_col2\" class=\"data row5 col2\" >9768-1967-07-04-23-09-00</td>\n",
- " <td id=\"T_003c4_row5_col3\" class=\"data row5 col3\" >4.326286</td>\n",
- " <td id=\"T_003c4_row5_col4\" class=\"data row5 col4\" >0.000000</td>\n",
- " <td id=\"T_003c4_row5_col5\" class=\"data row5 col5\" >1</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th id=\"T_003c4_level0_row6\" class=\"row_heading level0 row6\" >6</th>\n",
- " <td id=\"T_003c4_row6_col0\" class=\"data row6 col0\" >7916</td>\n",
- " <td id=\"T_003c4_row6_col1\" class=\"data row6 col1\" >1968-12-20 03:38:00</td>\n",
- " <td id=\"T_003c4_row6_col2\" class=\"data row6 col2\" >7916-1968-12-20-03-38-00</td>\n",
- " <td id=\"T_003c4_row6_col3\" class=\"data row6 col3\" >4.629502</td>\n",
- " <td id=\"T_003c4_row6_col4\" class=\"data row6 col4\" >0.000000</td>\n",
- " <td id=\"T_003c4_row6_col5\" class=\"data row6 col5\" >0</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th id=\"T_003c4_level0_row7\" class=\"row_heading level0 row7\" >7</th>\n",
- " <td id=\"T_003c4_row7_col0\" class=\"data row7 col0\" >33</td>\n",
- " <td id=\"T_003c4_row7_col1\" class=\"data row7 col1\" >1967-07-28 03:16:00</td>\n",
- " <td id=\"T_003c4_row7_col2\" class=\"data row7 col2\" >33-1967-07-28-03-16-00</td>\n",
- " <td id=\"T_003c4_row7_col3\" class=\"data row7 col3\" >4.628500</td>\n",
- " <td id=\"T_003c4_row7_col4\" class=\"data row7 col4\" >0.000000</td>\n",
- " <td id=\"T_003c4_row7_col5\" class=\"data row7 col5\" >0</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th id=\"T_003c4_level0_row8\" class=\"row_heading level0 row8\" >8</th>\n",
- " <td id=\"T_003c4_row8_col0\" class=\"data row8 col0\" >2883</td>\n",
- " <td id=\"T_003c4_row8_col1\" class=\"data row8 col1\" >1968-01-28 21:50:00</td>\n",
- " <td id=\"T_003c4_row8_col2\" class=\"data row8 col2\" >2883-1968-01-28-21-50-00</td>\n",
- " <td id=\"T_003c4_row8_col3\" class=\"data row8 col3\" >8.257742</td>\n",
- " <td id=\"T_003c4_row8_col4\" class=\"data row8 col4\" >0.000000</td>\n",
- " <td id=\"T_003c4_row8_col5\" class=\"data row8 col5\" >1</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th id=\"T_003c4_level0_row9\" class=\"row_heading level0 row9\" >9</th>\n",
- " <td id=\"T_003c4_row9_col0\" class=\"data row9 col0\" >1515</td>\n",
- " <td id=\"T_003c4_row9_col1\" class=\"data row9 col1\" >1968-07-18 08:28:00</td>\n",
- " <td id=\"T_003c4_row9_col2\" class=\"data row9 col2\" >1515-1968-07-18-08-28-00</td>\n",
- " <td id=\"T_003c4_row9_col3\" class=\"data row9 col3\" >2.973084</td>\n",
- " <td id=\"T_003c4_row9_col4\" class=\"data row9 col4\" >0.000000</td>\n",
- " <td id=\"T_003c4_row9_col5\" class=\"data row9 col5\" >0</td>\n",
+ " <th id=\"T_4dbad_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
+ " <td id=\"T_4dbad_row0_col0\" class=\"data row0 col0\" >9903</td>\n",
+ " <td id=\"T_4dbad_row0_col1\" class=\"data row0 col1\" >1968-05-09 21:24:00</td>\n",
+ " <td id=\"T_4dbad_row0_col2\" class=\"data row0 col2\" >9903-1968-05-09-21-24-00</td>\n",
+ " <td id=\"T_4dbad_row0_col3\" class=\"data row0 col3\" >0.990763</td>\n",
+ " <td id=\"T_4dbad_row0_col4\" class=\"data row0 col4\" >nan</td>\n",
+ " <td id=\"T_4dbad_row0_col5\" class=\"data row0 col5\" >0.000000</td>\n",
+ " <td id=\"T_4dbad_row0_col6\" class=\"data row0 col6\" >0</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th id=\"T_4dbad_level0_row1\" class=\"row_heading level0 row1\" >1</th>\n",
+ " <td id=\"T_4dbad_row1_col0\" class=\"data row1 col0\" >6447</td>\n",
+ " <td id=\"T_4dbad_row1_col1\" class=\"data row1 col1\" >1967-09-25 18:08:00</td>\n",
+ " <td id=\"T_4dbad_row1_col2\" class=\"data row1 col2\" >6447-1967-09-25-18-08-00</td>\n",
+ " <td id=\"T_4dbad_row1_col3\" class=\"data row1 col3\" >5.582745</td>\n",
+ " <td id=\"T_4dbad_row1_col4\" class=\"data row1 col4\" >7.577100</td>\n",
+ " <td id=\"T_4dbad_row1_col5\" class=\"data row1 col5\" >0.000000</td>\n",
+ " <td id=\"T_4dbad_row1_col6\" class=\"data row1 col6\" >1</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th id=\"T_4dbad_level0_row2\" class=\"row_heading level0 row2\" >2</th>\n",
+ " <td id=\"T_4dbad_row2_col0\" class=\"data row2 col0\" >4927</td>\n",
+ " <td id=\"T_4dbad_row2_col1\" class=\"data row2 col1\" >1968-06-30 12:13:00</td>\n",
+ " <td id=\"T_4dbad_row2_col2\" class=\"data row2 col2\" >4927-1968-06-30-12-13-00</td>\n",
+ " <td id=\"T_4dbad_row2_col3\" class=\"data row2 col3\" >4.957251</td>\n",
+ " <td id=\"T_4dbad_row2_col4\" class=\"data row2 col4\" >nan</td>\n",
+ " <td id=\"T_4dbad_row2_col5\" class=\"data row2 col5\" >0.000000</td>\n",
+ " <td id=\"T_4dbad_row2_col6\" class=\"data row2 col6\" >0</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th id=\"T_4dbad_level0_row3\" class=\"row_heading level0 row3\" >3</th>\n",
+ " <td id=\"T_4dbad_row3_col0\" class=\"data row3 col0\" >5475</td>\n",
+ " <td id=\"T_4dbad_row3_col1\" class=\"data row3 col1\" >1967-01-09 03:09:00</td>\n",
+ " <td id=\"T_4dbad_row3_col2\" class=\"data row3 col2\" >5475-1967-01-09-03-09-00</td>\n",
+ " <td id=\"T_4dbad_row3_col3\" class=\"data row3 col3\" >5.999336</td>\n",
+ " <td id=\"T_4dbad_row3_col4\" class=\"data row3 col4\" >9.497229</td>\n",
+ " <td id=\"T_4dbad_row3_col5\" class=\"data row3 col5\" >0.000000</td>\n",
+ " <td id=\"T_4dbad_row3_col6\" class=\"data row3 col6\" >0</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th id=\"T_4dbad_level0_row4\" class=\"row_heading level0 row4\" >4</th>\n",
+ " <td id=\"T_4dbad_row4_col0\" class=\"data row4 col0\" >9793</td>\n",
+ " <td id=\"T_4dbad_row4_col1\" class=\"data row4 col1\" >1968-12-15 12:59:00</td>\n",
+ " <td id=\"T_4dbad_row4_col2\" class=\"data row4 col2\" >9793-1968-12-15-12-59-00</td>\n",
+ " <td id=\"T_4dbad_row4_col3\" class=\"data row4 col3\" >7.294038</td>\n",
+ " <td id=\"T_4dbad_row4_col4\" class=\"data row4 col4\" >8.182348</td>\n",
+ " <td id=\"T_4dbad_row4_col5\" class=\"data row4 col5\" >0.000000</td>\n",
+ " <td id=\"T_4dbad_row4_col6\" class=\"data row4 col6\" >0</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th id=\"T_4dbad_level0_row5\" class=\"row_heading level0 row5\" >5</th>\n",
+ " <td id=\"T_4dbad_row5_col0\" class=\"data row5 col0\" >9768</td>\n",
+ " <td id=\"T_4dbad_row5_col1\" class=\"data row5 col1\" >1967-07-04 23:09:00</td>\n",
+ " <td id=\"T_4dbad_row5_col2\" class=\"data row5 col2\" >9768-1967-07-04-23-09-00</td>\n",
+ " <td id=\"T_4dbad_row5_col3\" class=\"data row5 col3\" >4.326286</td>\n",
+ " <td id=\"T_4dbad_row5_col4\" class=\"data row5 col4\" >nan</td>\n",
+ " <td id=\"T_4dbad_row5_col5\" class=\"data row5 col5\" >0.000000</td>\n",
+ " <td id=\"T_4dbad_row5_col6\" class=\"data row5 col6\" >1</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th id=\"T_4dbad_level0_row6\" class=\"row_heading level0 row6\" >6</th>\n",
+ " <td id=\"T_4dbad_row6_col0\" class=\"data row6 col0\" >7916</td>\n",
+ " <td id=\"T_4dbad_row6_col1\" class=\"data row6 col1\" >1968-12-20 03:38:00</td>\n",
+ " <td id=\"T_4dbad_row6_col2\" class=\"data row6 col2\" >7916-1968-12-20-03-38-00</td>\n",
+ " <td id=\"T_4dbad_row6_col3\" class=\"data row6 col3\" >4.629502</td>\n",
+ " <td id=\"T_4dbad_row6_col4\" class=\"data row6 col4\" >nan</td>\n",
+ " <td id=\"T_4dbad_row6_col5\" class=\"data row6 col5\" >0.000000</td>\n",
+ " <td id=\"T_4dbad_row6_col6\" class=\"data row6 col6\" >0</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th id=\"T_4dbad_level0_row7\" class=\"row_heading level0 row7\" >7</th>\n",
+ " <td id=\"T_4dbad_row7_col0\" class=\"data row7 col0\" >33</td>\n",
+ " <td id=\"T_4dbad_row7_col1\" class=\"data row7 col1\" >1967-07-28 03:16:00</td>\n",
+ " <td id=\"T_4dbad_row7_col2\" class=\"data row7 col2\" >33-1967-07-28-03-16-00</td>\n",
+ " <td id=\"T_4dbad_row7_col3\" class=\"data row7 col3\" >4.628500</td>\n",
+ " <td id=\"T_4dbad_row7_col4\" class=\"data row7 col4\" >nan</td>\n",
+ " <td id=\"T_4dbad_row7_col5\" class=\"data row7 col5\" >0.000000</td>\n",
+ " <td id=\"T_4dbad_row7_col6\" class=\"data row7 col6\" >0</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th id=\"T_4dbad_level0_row8\" class=\"row_heading level0 row8\" >8</th>\n",
+ " <td id=\"T_4dbad_row8_col0\" class=\"data row8 col0\" >2883</td>\n",
+ " <td id=\"T_4dbad_row8_col1\" class=\"data row8 col1\" >1968-01-28 21:50:00</td>\n",
+ " <td id=\"T_4dbad_row8_col2\" class=\"data row8 col2\" >2883-1968-01-28-21-50-00</td>\n",
+ " <td id=\"T_4dbad_row8_col3\" class=\"data row8 col3\" >8.257742</td>\n",
+ " <td id=\"T_4dbad_row8_col4\" class=\"data row8 col4\" >nan</td>\n",
+ " <td id=\"T_4dbad_row8_col5\" class=\"data row8 col5\" >0.000000</td>\n",
+ " <td id=\"T_4dbad_row8_col6\" class=\"data row8 col6\" >1</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th id=\"T_4dbad_level0_row9\" class=\"row_heading level0 row9\" >9</th>\n",
+ " <td id=\"T_4dbad_row9_col0\" class=\"data row9 col0\" >1515</td>\n",
+ " <td id=\"T_4dbad_row9_col1\" class=\"data row9 col1\" >1968-07-18 08:28:00</td>\n",
+ " <td id=\"T_4dbad_row9_col2\" class=\"data row9 col2\" >1515-1968-07-18-08-28-00</td>\n",
+ " <td id=\"T_4dbad_row9_col3\" class=\"data row9 col3\" >2.973084</td>\n",
+ " <td id=\"T_4dbad_row9_col4\" class=\"data row9 col4\" >0.671010</td>\n",
+ " <td id=\"T_4dbad_row9_col5\" class=\"data row9 col5\" >0.000000</td>\n",
+ " <td id=\"T_4dbad_row9_col6\" class=\"data row9 col6\" >0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n"
],
"text/plain": [
- "<pandas.io.formats.style.Styler at 0x107535f70>"
+ "<pandas.io.formats.style.Styler at 0x13b5dd9f0>"
]
},
- "execution_count": 14,
+ "execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
@@ -1399,12 +1451,14 @@
"source": [
"# For displayability, shorten col names\n",
"shortened_pred = \"pred_X\"\n",
+ "shortened_pred_interval = \"pred_X_30_to_90\"\n",
"shortened_outcome = \"outc_Y\"\n",
"\n",
"df = df.rename(\n",
" {\n",
- " \"pred_predictor_name_within_730_days_mean_fallback_nan\": shortened_pred,\n",
- " \"outc_outcome_name_within_365_days_maximum_fallback_0_dichotomous\": shortened_outcome,\n",
+ " \"pred_predictor_name_within_0_to_730_days_mean_fallback_nan\": shortened_pred,\n",
+ " \"pred_predictor_interval_name_within_30_to_90_days_mean_fallback_nan\": shortened_pred_interval,\n",
+ " \"outc_outcome_name_within_0_to_365_days_maximum_fallback_0_dichotomous\": shortened_outcome,\n",
" },\n",
" axis=1,\n",
")\n",
@@ -1424,6 +1478,11 @@
"4. Our predictor columns, prefixed with `pred_` and\n",
"5. Our outcome columns, prefixed with `outc_`"
]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": []
}
],
"metadata": {
@@ -1442,7 +1501,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.9.17"
+ "version": "3.10.13"
},
"orig_nbformat": 4,
"vscode": {
diff --git a/docs/tutorials/02_advanced.ipynb b/docs/tutorials/02_advanced.ipynb
index 9c2a725..1147e11 100644
--- a/docs/tutorials/02_advanced.ipynb
+++ b/docs/tutorials/02_advanced.ipynb
@@ -32,7 +32,7 @@
},
{
"cell_type": "code",
- "execution_count": 24,
+ "execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
@@ -47,7 +47,7 @@
},
{
"cell_type": "code",
- "execution_count": 25,
+ "execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
@@ -55,7 +55,7 @@
" named_dataframes=[\n",
" NamedDataframe(df=load_synth_predictor_float(), name=\"synth_predictor_float\")\n",
" ],\n",
- " lookbehind_days=[365, 730],\n",
+ " lookbehind_days=[(0, 365), (365, 730), 1095],\n",
" fallback=[np.nan],\n",
" aggregation_fns=[mean, maximum],\n",
").create_combinations()"
@@ -76,26 +76,32 @@
},
{
"cell_type": "code",
- "execution_count": 26,
+ "execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
- "––––––––– We created 4 combinations of predictors. ––––––––––\n",
+ "––––––––– We created 6 combinations of predictors. ––––––––––\n",
"[{'aggregation_fn': 'mean',\n",
" 'feature_name': 'synth_predictor_float',\n",
- " 'lookbehind_days': 365.0},\n",
+ " 'lookbehind_days': LookPeriod(min_days=0.0, max_days=365.0)},\n",
" {'aggregation_fn': 'maximum',\n",
" 'feature_name': 'synth_predictor_float',\n",
- " 'lookbehind_days': 365.0},\n",
+ " 'lookbehind_days': LookPeriod(min_days=0.0, max_days=365.0)},\n",
" {'aggregation_fn': 'mean',\n",
" 'feature_name': 'synth_predictor_float',\n",
- " 'lookbehind_days': 730.0},\n",
+ " 'lookbehind_days': LookPeriod(min_days=365.0, max_days=730.0)},\n",
" {'aggregation_fn': 'maximum',\n",
" 'feature_name': 'synth_predictor_float',\n",
- " 'lookbehind_days': 730.0}]\n"
+ " 'lookbehind_days': LookPeriod(min_days=365.0, max_days=730.0)},\n",
+ " {'aggregation_fn': 'mean',\n",
+ " 'feature_name': 'synth_predictor_float',\n",
+ " 'lookbehind_days': LookPeriod(min_days=0, max_days=1095.0)},\n",
+ " {'aggregation_fn': 'maximum',\n",
+ " 'feature_name': 'synth_predictor_float',\n",
+ " 'lookbehind_days': LookPeriod(min_days=0, max_days=1095.0)}]\n"
]
}
],
@@ -104,7 +110,7 @@
"pred_spec_batch_summary = [\n",
" {\n",
" \"feature_name\": pred_spec.feature_base_name,\n",
- " \"lookbehind_days\": pred_spec.lookbehind_days,\n",
+ " \"lookbehind_days\": pred_spec.lookbehind_period,\n",
" \"aggregation_fn\": pred_spec.aggregation_fn.__name__,\n",
" }\n",
" for pred_spec in pred_spec_batch\n",
@@ -141,7 +147,7 @@
},
{
"cell_type": "code",
- "execution_count": 27,
+ "execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
@@ -154,14 +160,14 @@
},
{
"cell_type": "code",
- "execution_count": 28,
+ "execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
- "2023-06-14 16:19:04 [INFO] Overriding pred_time_uuid_col_name in cache with pred_time_uuid_col_name passed to init of flattened dataset\n"
+ "2024-01-18 11:38:02 [INFO] Overriding pred_time_uuid_col_name in cache with pred_time_uuid_col_name passed to init of flattened dataset\n"
]
}
],
@@ -192,7 +198,7 @@
},
{
"cell_type": "code",
- "execution_count": 29,
+ "execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
@@ -201,21 +207,30 @@
},
{
"cell_type": "code",
- "execution_count": 30,
+ "execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
- "2023-06-14 16:19:04 [INFO] There were unprocessed specs, computing...\n",
- "2023-06-14 16:19:04 [INFO] _drop_pred_time_if_insufficient_look_distance: Dropped 4038 (40.38%) rows\n",
- "2023-06-14 16:19:04 [INFO] Processing 4 temporal features in parallel with 4 workers. Chunksize is 1. If this is above 1, it may take some time for the progress bar to move, as processing is batched. However, this makes for much faster total performance.\n",
- "100%|██████████| 4/4 [00:01<00:00, 2.75it/s]\n",
- "2023-06-14 16:19:05 [INFO] Checking alignment of dataframes - this might take a little while (~2 minutes for 1.000 dataframes with 2.000.000 rows).\n",
- "2023-06-14 16:19:05 [INFO] Starting concatenation. Will take some time on performant systems, e.g. 30s for 100 features and 2_000_000 prediction times. This is normal.\n",
- "2023-06-14 16:19:05 [INFO] Concatenation took 0.007 seconds\n",
- "2023-06-14 16:19:05 [INFO] Merging with original df\n"
+ "2024-01-18 11:38:03 [INFO] There were unprocessed specs, computing...\n",
+ "2024-01-18 11:38:03 [INFO] _drop_pred_time_if_insufficient_look_distance: Dropped 6053 (60.53%) rows\n",
+ "2024-01-18 11:38:03 [INFO] Processing 6 temporal features in parallel with 4 workers. Chunksize is 2. If this is above 1, it may take some time for the progress bar to move, as processing is batched. However, this makes for much faster total performance.\n",
+ " 0%| | 0/6 [00:00<?, ?it/s]/Users/au554730/Desktop/Projects/timeseriesflattener/.venv/lib/python3.10/site-packages/pydantic/_internal/_config.py:269: UserWarning: Valid config keys have changed in V2:\n",
+ "* 'allow_mutation' has been removed\n",
+ " warnings.warn(message, UserWarning)\n",
+ "/Users/au554730/Desktop/Projects/timeseriesflattener/.venv/lib/python3.10/site-packages/pydantic/_internal/_config.py:269: UserWarning: Valid config keys have changed in V2:\n",
+ "* 'allow_mutation' has been removed\n",
+ " warnings.warn(message, UserWarning)\n",
+ "/Users/au554730/Desktop/Projects/timeseriesflattener/.venv/lib/python3.10/site-packages/pydantic/_internal/_config.py:269: UserWarning: Valid config keys have changed in V2:\n",
+ "* 'allow_mutation' has been removed\n",
+ " warnings.warn(message, UserWarning)\n",
+ "100%|██████████| 6/6 [00:02<00:00, 2.17it/s]\n",
+ "2024-01-18 11:38:05 [INFO] Checking alignment of dataframes - this might take a little while (~2 minutes for 1.000 dataframes with 2.000.000 rows).\n",
+ "2024-01-18 11:38:05 [INFO] Starting concatenation. Will take some time on performant systems, e.g. 30s for 100 features and 2_000_000 prediction times. This is normal.\n",
+ "2024-01-18 11:38:05 [INFO] Concatenation took 0.01 seconds\n",
+ "2024-01-18 11:38:05 [INFO] Merging with original df\n"
]
}
],
@@ -225,7 +240,7 @@
},
{
"cell_type": "code",
- "execution_count": 31,
+ "execution_count": 16,
"metadata": {},
"outputs": [
{
@@ -236,32 +251,34 @@
"│ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ │\n",
"│ ┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> dataframe </span>┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Values </span>┃ ┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Column Type </span>┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Count </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ │\n",
- "│ │ Number of rows │ 5962 │ │ float64 │ 4 │ │\n",
- "│ │ Number of columns │ 7 │ │ int64 │ 1 │ │\n",
+ "│ │ Number of rows │ 3947 │ │ float64 │ 6 │ │\n",
+ "│ │ Number of columns │ 9 │ │ int64 │ 1 │ │\n",
"│ └───────────────────┴────────┘ │ datetime64 │ 1 │ │\n",
"│ │ string │ 1 │ │\n",
"│ └─────────────┴───────┘ │\n",
"│ <span style=\"font-style: italic\"> number </span> │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
- "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">entity_id </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7400</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█▇███▇ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 820</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 14</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.00039</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.4</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▂▄██▄▂ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 110</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7.7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.058</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.3</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ▁▁▂▄█ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 820</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 14</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.00039</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 4.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 8.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▂▃▄▆█ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 110</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.058</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.9</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.9</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▃██▃▁ </span> │ │\n",
- "│ └───────────────────────────┴───────┴────────┴────────┴───────┴───────────┴───────┴───────┴────────┴─────────┘ │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┓ │\n",
+ "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━┩ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">entity_id </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2600</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7400</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█████▇</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.18</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.3</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.29</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 4.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.9</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ▂█▇▁ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 510</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 13</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.024</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 4.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 8.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▂▂▃▄▆█</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 530</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 14</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.0084</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 4.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 8.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▂▃▄▆█</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.18</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 8.4</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.29</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ▁▃█</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 510</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 13</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.2</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.024</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▂▄██▅▂</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 530</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 14</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.0084</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.4</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.9</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▂▄██▄▂</span> │ │\n",
+ "│ └────────────────────────────┴───────┴────────┴────────┴────────┴──────────┴───────┴───────┴────────┴────────┘ │\n",
"│ <span style=\"font-style: italic\"> datetime </span> │\n",
"│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
"│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> first </span>┃<span style=\"font-weight: bold\"> last </span>┃<span style=\"font-weight: bold\"> frequency </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">timestamp </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1967-01-02 01:16:00 </span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1969-12-31 21:42:00 </span> │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">None </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">timestamp </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1968-01-02 05:12:00 </span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1969-12-31 21:42:00 </span> │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">None </span> │ │\n",
"│ └──────────────────┴──────┴─────────┴────────────────────────────┴────────────────────────────┴──────────────┘ │\n",
"│ <span style=\"font-style: italic\"> string </span> │\n",
"│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓ │\n",
"│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> words per row </span>┃<span style=\"font-weight: bold\"> total words </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">prediction_time_uuid </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6000</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">prediction_time_uuid </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3900</span> │ │\n",
"│ └───────────────────────────────────────┴───────┴───────────┴──────────────────────────┴─────────────────────┘ │\n",
"╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯\n",
"</pre>\n"
@@ -272,32 +289,34 @@
"│ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ │\n",
"│ ┃\u001b[1;36m \u001b[0m\u001b[1;36mdataframe \u001b[0m\u001b[1;36m \u001b[0m┃\u001b[1;36m \u001b[0m\u001b[1;36mValues\u001b[0m\u001b[1;36m \u001b[0m┃ ┃\u001b[1;36m \u001b[0m\u001b[1;36mColumn Type\u001b[0m\u001b[1;36m \u001b[0m┃\u001b[1;36m \u001b[0m\u001b[1;36mCount\u001b[0m\u001b[1;36m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ │\n",
- "│ │ Number of rows │ 5962 │ │ float64 │ 4 │ │\n",
- "│ │ Number of columns │ 7 │ │ int64 │ 1 │ │\n",
+ "│ │ Number of rows │ 3947 │ │ float64 │ 6 │ │\n",
+ "│ │ Number of columns │ 9 │ │ int64 │ 1 │ │\n",
"│ └───────────────────┴────────┘ │ datetime64 │ 1 │ │\n",
"│ │ string │ 1 │ │\n",
"│ └─────────────┴───────┘ │\n",
"│ \u001b[3m number \u001b[0m │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
- "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mentity_id \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7400\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m█▇███▇ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 820\u001b[0m │ \u001b[36m 14\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 2.1\u001b[0m │ \u001b[36m 0.00039\u001b[0m │ \u001b[36m 3.5\u001b[0m │ \u001b[36m 6.4\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m▂▄██▄▂ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 110\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 7.7\u001b[0m │ \u001b[36m 2.1\u001b[0m │ \u001b[36m 0.058\u001b[0m │ \u001b[36m 6.7\u001b[0m │ \u001b[36m 9.3\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m ▁▁▂▄█ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 820\u001b[0m │ \u001b[36m 14\u001b[0m │ \u001b[36m 6.6\u001b[0m │ \u001b[36m 2.6\u001b[0m │ \u001b[36m 0.00039\u001b[0m │ \u001b[36m 4.8\u001b[0m │ \u001b[36m 8.8\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m▁▂▃▄▆█ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 110\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 1.7\u001b[0m │ \u001b[36m 0.058\u001b[0m │ \u001b[36m 3.9\u001b[0m │ \u001b[36m 6.1\u001b[0m │ \u001b[36m 9.9\u001b[0m │ \u001b[32m▁▃██▃▁ \u001b[0m │ │\n",
- "│ └───────────────────────────┴───────┴────────┴────────┴───────┴───────────┴───────┴───────┴────────┴─────────┘ │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┓ │\n",
+ "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━┩ │\n",
+ "│ │ \u001b[38;5;141mentity_id \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2600\u001b[0m │ \u001b[36m 7400\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m█████▇\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 7\u001b[0m │ \u001b[36m 0.18\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 1.3\u001b[0m │ \u001b[36m 0.29\u001b[0m │ \u001b[36m 4.1\u001b[0m │ \u001b[36m 5.8\u001b[0m │ \u001b[36m 9.9\u001b[0m │ \u001b[32m ▂█▇▁ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 510\u001b[0m │ \u001b[36m 13\u001b[0m │ \u001b[36m 6.6\u001b[0m │ \u001b[36m 2.6\u001b[0m │ \u001b[36m 0.024\u001b[0m │ \u001b[36m 4.8\u001b[0m │ \u001b[36m 8.8\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m▂▂▃▄▆█\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 530\u001b[0m │ \u001b[36m 14\u001b[0m │ \u001b[36m 6.6\u001b[0m │ \u001b[36m 2.6\u001b[0m │ \u001b[36m 0.0084\u001b[0m │ \u001b[36m 4.8\u001b[0m │ \u001b[36m 8.8\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m▁▂▃▄▆█\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 7\u001b[0m │ \u001b[36m 0.18\u001b[0m │ \u001b[36m 8.4\u001b[0m │ \u001b[36m 1.5\u001b[0m │ \u001b[36m 0.29\u001b[0m │ \u001b[36m 7.8\u001b[0m │ \u001b[36m 9.5\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m ▁▃█\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 510\u001b[0m │ \u001b[36m 13\u001b[0m │ \u001b[36m 5.1\u001b[0m │ \u001b[36m 2.2\u001b[0m │ \u001b[36m 0.024\u001b[0m │ \u001b[36m 3.6\u001b[0m │ \u001b[36m 6.5\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m▂▄██▅▂\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 530\u001b[0m │ \u001b[36m 14\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 2.1\u001b[0m │ \u001b[36m 0.0084\u001b[0m │ \u001b[36m 3.6\u001b[0m │ \u001b[36m 6.4\u001b[0m │ \u001b[36m 9.9\u001b[0m │ \u001b[32m▂▄██▄▂\u001b[0m │ │\n",
+ "│ └────────────────────────────┴───────┴────────┴────────┴────────┴──────────┴───────┴───────┴────────┴────────┘ │\n",
"│ \u001b[3m datetime \u001b[0m │\n",
"│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
"│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mfirst \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mlast \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mfrequency \u001b[0m\u001b[1m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mtimestamp \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[31m 1967-01-02 01:16:00 \u001b[0m │ \u001b[31m 1969-12-31 21:42:00 \u001b[0m │ \u001b[38;5;141mNone \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mtimestamp \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[31m 1968-01-02 05:12:00 \u001b[0m │ \u001b[31m 1969-12-31 21:42:00 \u001b[0m │ \u001b[38;5;141mNone \u001b[0m │ │\n",
"│ └──────────────────┴──────┴─────────┴────────────────────────────┴────────────────────────────┴──────────────┘ │\n",
"│ \u001b[3m string \u001b[0m │\n",
"│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓ │\n",
"│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mwords per row \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mtotal words \u001b[0m\u001b[1m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mprediction_time_uuid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 6000\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mprediction_time_uuid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 3900\u001b[0m │ │\n",
"│ └───────────────────────────────────────┴───────┴───────────┴──────────────────────────┴─────────────────────┘ │\n",
"╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯\n"
]
@@ -311,13 +330,15 @@
"['entity_id',\n",
" 'timestamp',\n",
" 'prediction_time_uuid',\n",
- " 'pred_synth_predictor_float_within_365_days_mean_fallback_nan',\n",
- " 'pred_synth_predictor_float_within_730_days_maximum_fallback_nan',\n",
- " 'pred_synth_predictor_float_within_365_days_maximum_fallback_nan',\n",
- " 'pred_synth_predictor_float_within_730_days_mean_fallback_nan']"
+ " 'pred_synth_predictor_float_within_0_to_1095_days_mean_fallback_nan',\n",
+ " 'pred_synth_predictor_float_within_365_to_730_days_maximum_fallback_nan',\n",
+ " 'pred_synth_predictor_float_within_0_to_365_days_maximum_fallback_nan',\n",
+ " 'pred_synth_predictor_float_within_0_to_1095_days_maximum_fallback_nan',\n",
+ " 'pred_synth_predictor_float_within_365_to_730_days_mean_fallback_nan',\n",
+ " 'pred_synth_predictor_float_within_0_to_365_days_mean_fallback_nan']"
]
},
- "execution_count": 31,
+ "execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
@@ -330,7 +351,7 @@
},
{
"cell_type": "code",
- "execution_count": 32,
+ "execution_count": 17,
"metadata": {},
"outputs": [
{
@@ -338,128 +359,150 @@
"text/html": [
"<style type=\"text/css\">\n",
"</style>\n",
- "<table id=\"T_f5435\" style=\"font-size: 14px\">\n",
+ "<table id=\"T_c1c6b\" style=\"font-size: 14px\">\n",
" <thead>\n",
" <tr>\n",
" <th class=\"blank level0\" > </th>\n",
- " <th id=\"T_f5435_level0_col0\" class=\"col_heading level0 col0\" >entity_id</th>\n",
- " <th id=\"T_f5435_level0_col1\" class=\"col_heading level0 col1\" >timestamp</th>\n",
- " <th id=\"T_f5435_level0_col2\" class=\"col_heading level0 col2\" >prediction_time_uuid</th>\n",
- " <th id=\"T_f5435_level0_col3\" class=\"col_heading level0 col3\" >pred_1</th>\n",
- " <th id=\"T_f5435_level0_col4\" class=\"col_heading level0 col4\" >pred_2</th>\n",
- " <th id=\"T_f5435_level0_col5\" class=\"col_heading level0 col5\" >pred_3</th>\n",
- " <th id=\"T_f5435_level0_col6\" class=\"col_heading level0 col6\" >pred_4</th>\n",
+ " <th id=\"T_c1c6b_level0_col0\" class=\"col_heading level0 col0\" >entity_id</th>\n",
+ " <th id=\"T_c1c6b_level0_col1\" class=\"col_heading level0 col1\" >timestamp</th>\n",
+ " <th id=\"T_c1c6b_level0_col2\" class=\"col_heading level0 col2\" >prediction_time_uuid</th>\n",
+ " <th id=\"T_c1c6b_level0_col3\" class=\"col_heading level0 col3\" >pred_1</th>\n",
+ " <th id=\"T_c1c6b_level0_col4\" class=\"col_heading level0 col4\" >pred_2</th>\n",
+ " <th id=\"T_c1c6b_level0_col5\" class=\"col_heading level0 col5\" >pred_3</th>\n",
+ " <th id=\"T_c1c6b_level0_col6\" class=\"col_heading level0 col6\" >pred_4</th>\n",
+ " <th id=\"T_c1c6b_level0_col7\" class=\"col_heading level0 col7\" >pred_5</th>\n",
+ " <th id=\"T_c1c6b_level0_col8\" class=\"col_heading level0 col8\" >pred_6</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
- " <th id=\"T_f5435_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
- " <td id=\"T_f5435_row0_col0\" class=\"data row0 col0\" >9903</td>\n",
- " <td id=\"T_f5435_row0_col1\" class=\"data row0 col1\" >1968-05-09 21:24:00</td>\n",
- " <td id=\"T_f5435_row0_col2\" class=\"data row0 col2\" >9903-1968-05-09-21-24-00</td>\n",
- " <td id=\"T_f5435_row0_col3\" class=\"data row0 col3\" >0.154981</td>\n",
- " <td id=\"T_f5435_row0_col4\" class=\"data row0 col4\" >2.194319</td>\n",
- " <td id=\"T_f5435_row0_col5\" class=\"data row0 col5\" >0.154981</td>\n",
- " <td id=\"T_f5435_row0_col6\" class=\"data row0 col6\" >0.990763</td>\n",
+ " <th id=\"T_c1c6b_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
+ " <td id=\"T_c1c6b_row0_col0\" class=\"data row0 col0\" >9903</td>\n",
+ " <td id=\"T_c1c6b_row0_col1\" class=\"data row0 col1\" >1968-05-09 21:24:00</td>\n",
+ " <td id=\"T_c1c6b_row0_col2\" class=\"data row0 col2\" >9903-1968-05-09-21-24-00</td>\n",
+ " <td id=\"T_c1c6b_row0_col3\" class=\"data row0 col3\" >2.864626</td>\n",
+ " <td id=\"T_c1c6b_row0_col4\" class=\"data row0 col4\" >2.194319</td>\n",
+ " <td id=\"T_c1c6b_row0_col5\" class=\"data row0 col5\" >0.154981</td>\n",
+ " <td id=\"T_c1c6b_row0_col6\" class=\"data row0 col6\" >5.931553</td>\n",
+ " <td id=\"T_c1c6b_row0_col7\" class=\"data row0 col7\" >1.408655</td>\n",
+ " <td id=\"T_c1c6b_row0_col8\" class=\"data row0 col8\" >0.154981</td>\n",
" </tr>\n",
" <tr>\n",
- " <th id=\"T_f5435_level0_row1\" class=\"row_heading level0 row1\" >1</th>\n",
- " <td id=\"T_f5435_row1_col0\" class=\"data row1 col0\" >6447</td>\n",
- " <td id=\"T_f5435_row1_col1\" class=\"data row1 col1\" >1967-09-25 18:08:00</td>\n",
- " <td id=\"T_f5435_row1_col2\" class=\"data row1 col2\" >6447-1967-09-25-18-08-00</td>\n",
- " <td id=\"T_f5435_row1_col3\" class=\"data row1 col3\" >5.396017</td>\n",
- " <td id=\"T_f5435_row1_col4\" class=\"data row1 col4\" >9.774050</td>\n",
- " <td id=\"T_f5435_row1_col5\" class=\"data row1 col5\" >8.930256</td>\n",
- " <td id=\"T_f5435_row1_col6\" class=\"data row1 col6\" >5.582745</td>\n",
+ " <th id=\"T_c1c6b_level0_row1\" class=\"row_heading level0 row1\" >1</th>\n",
+ " <td id=\"T_c1c6b_row1_col0\" class=\"data row1 col0\" >4927</td>\n",
+ " <td id=\"T_c1c6b_row1_col1\" class=\"data row1 col1\" >1968-06-30 12:13:00</td>\n",
+ " <td id=\"T_c1c6b_row1_col2\" class=\"data row1 col2\" >4927-1968-06-30-12-13-00</td>\n",
+ " <td id=\"T_c1c6b_row1_col3\" class=\"data row1 col3\" >4.466599</td>\n",
+ " <td id=\"T_c1c6b_row1_col4\" class=\"data row1 col4\" >nan</td>\n",
+ " <td id=\"T_c1c6b_row1_col5\" class=\"data row1 col5\" >6.730694</td>\n",
+ " <td id=\"T_c1c6b_row1_col6\" class=\"data row1 col6\" >8.630901</td>\n",
+ " <td id=\"T_c1c6b_row1_col7\" class=\"data row1 col7\" >nan</td>\n",
+ " <td id=\"T_c1c6b_row1_col8\" class=\"data row1 col8\" >4.957251</td>\n",
" </tr>\n",
" <tr>\n",
- " <th id=\"T_f5435_level0_row2\" class=\"row_heading level0 row2\" >2</th>\n",
- " <td id=\"T_f5435_row2_col0\" class=\"data row2 col0\" >4927</td>\n",
- " <td id=\"T_f5435_row2_col1\" class=\"data row2 col1\" >1968-06-30 12:13:00</td>\n",
- " <td id=\"T_f5435_row2_col2\" class=\"data row2 col2\" >4927-1968-06-30-12-13-00</td>\n",
- " <td id=\"T_f5435_row2_col3\" class=\"data row2 col3\" >4.957251</td>\n",
- " <td id=\"T_f5435_row2_col4\" class=\"data row2 col4\" >6.730694</td>\n",
- " <td id=\"T_f5435_row2_col5\" class=\"data row2 col5\" >6.730694</td>\n",
- " <td id=\"T_f5435_row2_col6\" class=\"data row2 col6\" >4.957251</td>\n",
+ " <th id=\"T_c1c6b_level0_row2\" class=\"row_heading level0 row2\" >2</th>\n",
+ " <td id=\"T_c1c6b_row2_col0\" class=\"data row2 col0\" >3157</td>\n",
+ " <td id=\"T_c1c6b_row2_col1\" class=\"data row2 col1\" >1969-10-07 05:01:00</td>\n",
+ " <td id=\"T_c1c6b_row2_col2\" class=\"data row2 col2\" >3157-1969-10-07-05-01-00</td>\n",
+ " <td id=\"T_c1c6b_row2_col3\" class=\"data row2 col3\" >4.168456</td>\n",
+ " <td id=\"T_c1c6b_row2_col4\" class=\"data row2 col4\" >nan</td>\n",
+ " <td id=\"T_c1c6b_row2_col5\" class=\"data row2 col5\" >5.243176</td>\n",
+ " <td id=\"T_c1c6b_row2_col6\" class=\"data row2 col6\" >5.243176</td>\n",
+ " <td id=\"T_c1c6b_row2_col7\" class=\"data row2 col7\" >nan</td>\n",
+ " <td id=\"T_c1c6b_row2_col8\" class=\"data row2 col8\" >5.068323</td>\n",
" </tr>\n",
" <tr>\n",
- " <th id=\"T_f5435_level0_row3\" class=\"row_heading level0 row3\" >3</th>\n",
- " <td id=\"T_f5435_row3_col0\" class=\"data row3 col0\" >5475</td>\n",
- " <td id=\"T_f5435_row3_col1\" class=\"data row3 col1\" >1967-01-09 03:09:00</td>\n",
- " <td id=\"T_f5435_row3_col2\" class=\"data row3 col2\" >5475-1967-01-09-03-09-00</td>\n",
- " <td id=\"T_f5435_row3_col3\" class=\"data row3 col3\" >6.081539</td>\n",
- " <td id=\"T_f5435_row3_col4\" class=\"data row3 col4\" >9.497229</td>\n",
- " <td id=\"T_f5435_row3_col5\" class=\"data row3 col5\" >9.497229</td>\n",
- " <td id=\"T_f5435_row3_col6\" class=\"data row3 col6\" >5.999336</td>\n",
+ " <th id=\"T_c1c6b_level0_row3\" class=\"row_heading level0 row3\" >3</th>\n",
+ " <td id=\"T_c1c6b_row3_col0\" class=\"data row3 col0\" >9793</td>\n",
+ " <td id=\"T_c1c6b_row3_col1\" class=\"data row3 col1\" >1968-12-15 12:59:00</td>\n",
+ " <td id=\"T_c1c6b_row3_col2\" class=\"data row3 col2\" >9793-1968-12-15-12-59-00</td>\n",
+ " <td id=\"T_c1c6b_row3_col3\" class=\"data row3 col3\" >7.144959</td>\n",
+ " <td id=\"T_c1c6b_row3_col4\" class=\"data row3 col4\" >8.293266</td>\n",
+ " <td id=\"T_c1c6b_row3_col5\" class=\"data row3 col5\" >9.708976</td>\n",
+ " <td id=\"T_c1c6b_row3_col6\" class=\"data row3 col6\" >9.727182</td>\n",
+ " <td id=\"T_c1c6b_row3_col7\" class=\"data row3 col7\" >6.230417</td>\n",
+ " <td id=\"T_c1c6b_row3_col8\" class=\"data row3 col8\" >8.091755</td>\n",
" </tr>\n",
" <tr>\n",
- " <th id=\"T_f5435_level0_row4\" class=\"row_heading level0 row4\" >4</th>\n",
- " <td id=\"T_f5435_row4_col0\" class=\"data row4 col0\" >3157</td>\n",
- " <td id=\"T_f5435_row4_col1\" class=\"data row4 col1\" >1969-10-07 05:01:00</td>\n",
- " <td id=\"T_f5435_row4_col2\" class=\"data row4 col2\" >3157-1969-10-07-05-01-00</td>\n",
- " <td id=\"T_f5435_row4_col3\" class=\"data row4 col3\" >5.068323</td>\n",
- " <td id=\"T_f5435_row4_col4\" class=\"data row4 col4\" >5.243176</td>\n",
- " <td id=\"T_f5435_row4_col5\" class=\"data row4 col5\" >5.243176</td>\n",
- " <td id=\"T_f5435_row4_col6\" class=\"data row4 col6\" >5.068323</td>\n",
+ " <th id=\"T_c1c6b_level0_row4\" class=\"row_heading level0 row4\" >4</th>\n",
+ " <td id=\"T_c1c6b_row4_col0\" class=\"data row4 col0\" >9861</td>\n",
+ " <td id=\"T_c1c6b_row4_col1\" class=\"data row4 col1\" >1969-01-22 17:34:00</td>\n",
+ " <td id=\"T_c1c6b_row4_col2\" class=\"data row4 col2\" >9861-1969-01-22-17-34-00</td>\n",
+ " <td id=\"T_c1c6b_row4_col3\" class=\"data row4 col3\" >3.669635</td>\n",
+ " <td id=\"T_c1c6b_row4_col4\" class=\"data row4 col4\" >5.491415</td>\n",
+ " <td id=\"T_c1c6b_row4_col5\" class=\"data row4 col5\" >3.130283</td>\n",
+ " <td id=\"T_c1c6b_row4_col6\" class=\"data row4 col6\" >6.217161</td>\n",
+ " <td id=\"T_c1c6b_row4_col7\" class=\"data row4 col7\" >3.309197</td>\n",
+ " <td id=\"T_c1c6b_row4_col8\" class=\"data row4 col8\" >3.130283</td>\n",
" </tr>\n",
" <tr>\n",
- " <th id=\"T_f5435_level0_row5\" class=\"row_heading level0 row5\" >5</th>\n",
- " <td id=\"T_f5435_row5_col0\" class=\"data row5 col0\" >9793</td>\n",
- " <td id=\"T_f5435_row5_col1\" class=\"data row5 col1\" >1968-12-15 12:59:00</td>\n",
- " <td id=\"T_f5435_row5_col2\" class=\"data row5 col2\" >9793-1968-12-15-12-59-00</td>\n",
- " <td id=\"T_f5435_row5_col3\" class=\"data row5 col3\" >8.091755</td>\n",
- " <td id=\"T_f5435_row5_col4\" class=\"data row5 col4\" >9.708976</td>\n",
- " <td id=\"T_f5435_row5_col5\" class=\"data row5 col5\" >9.708976</td>\n",
- " <td id=\"T_f5435_row5_col6\" class=\"data row5 col6\" >7.294038</td>\n",
+ " <th id=\"T_c1c6b_level0_row5\" class=\"row_heading level0 row5\" >5</th>\n",
+ " <td id=\"T_c1c6b_row5_col0\" class=\"data row5 col0\" >657</td>\n",
+ " <td id=\"T_c1c6b_row5_col1\" class=\"data row5 col1\" >1969-04-14 15:47:00</td>\n",
+ " <td id=\"T_c1c6b_row5_col2\" class=\"data row5 col2\" >657-1969-04-14-15-47-00</td>\n",
+ " <td id=\"T_c1c6b_row5_col3\" class=\"data row5 col3\" >7.391514</td>\n",
+ " <td id=\"T_c1c6b_row5_col4\" class=\"data row5 col4\" >7.903614</td>\n",
+ " <td id=\"T_c1c6b_row5_col5\" class=\"data row5 col5\" >nan</td>\n",
+ " <td id=\"T_c1c6b_row5_col6\" class=\"data row5 col6\" >7.903614</td>\n",
+ " <td id=\"T_c1c6b_row5_col7\" class=\"data row5 col7\" >7.903614</td>\n",
+ " <td id=\"T_c1c6b_row5_col8\" class=\"data row5 col8\" >nan</td>\n",
" </tr>\n",
" <tr>\n",
- " <th id=\"T_f5435_level0_row6\" class=\"row_heading level0 row6\" >6</th>\n",
- " <td id=\"T_f5435_row6_col0\" class=\"data row6 col0\" >9768</td>\n",
- " <td id=\"T_f5435_row6_col1\" class=\"data row6 col1\" >1967-07-04 23:09:00</td>\n",
- " <td id=\"T_f5435_row6_col2\" class=\"data row6 col2\" >9768-1967-07-04-23-09-00</td>\n",
- " <td id=\"T_f5435_row6_col3\" class=\"data row6 col3\" >4.959419</td>\n",
- " <td id=\"T_f5435_row6_col4\" class=\"data row6 col4\" >5.729441</td>\n",
- " <td id=\"T_f5435_row6_col5\" class=\"data row6 col5\" >5.729441</td>\n",
- " <td id=\"T_f5435_row6_col6\" class=\"data row6 col6\" >4.326286</td>\n",
+ " <th id=\"T_c1c6b_level0_row6\" class=\"row_heading level0 row6\" >6</th>\n",
+ " <td id=\"T_c1c6b_row6_col0\" class=\"data row6 col0\" >7916</td>\n",
+ " <td id=\"T_c1c6b_row6_col1\" class=\"data row6 col1\" >1968-12-20 03:38:00</td>\n",
+ " <td id=\"T_c1c6b_row6_col2\" class=\"data row6 col2\" >7916-1968-12-20-03-38-00</td>\n",
+ " <td id=\"T_c1c6b_row6_col3\" class=\"data row6 col3\" >4.251704</td>\n",
+ " <td id=\"T_c1c6b_row6_col4\" class=\"data row6 col4\" >6.084523</td>\n",
+ " <td id=\"T_c1c6b_row6_col5\" class=\"data row6 col5\" >4.318586</td>\n",
+ " <td id=\"T_c1c6b_row6_col6\" class=\"data row6 col6\" >6.979156</td>\n",
+ " <td id=\"T_c1c6b_row6_col7\" class=\"data row6 col7\" >6.084523</td>\n",
+ " <td id=\"T_c1c6b_row6_col8\" class=\"data row6 col8\" >3.901992</td>\n",
" </tr>\n",
" <tr>\n",
- " <th id=\"T_f5435_level0_row7\" class=\"row_heading level0 row7\" >7</th>\n",
- " <td id=\"T_f5435_row7_col0\" class=\"data row7 col0\" >9861</td>\n",
- " <td id=\"T_f5435_row7_col1\" class=\"data row7 col1\" >1969-01-22 17:34:00</td>\n",
- " <td id=\"T_f5435_row7_col2\" class=\"data row7 col2\" >9861-1969-01-22-17-34-00</td>\n",
- " <td id=\"T_f5435_row7_col3\" class=\"data row7 col3\" >3.130283</td>\n",
- " <td id=\"T_f5435_row7_col4\" class=\"data row7 col4\" >5.491415</td>\n",
- " <td id=\"T_f5435_row7_col5\" class=\"data row7 col5\" >3.130283</td>\n",
- " <td id=\"T_f5435_row7_col6\" class=\"data row7 col6\" >3.279378</td>\n",
+ " <th id=\"T_c1c6b_level0_row7\" class=\"row_heading level0 row7\" >7</th>\n",
+ " <td id=\"T_c1c6b_row7_col0\" class=\"data row7 col0\" >2883</td>\n",
+ " <td id=\"T_c1c6b_row7_col1\" class=\"data row7 col1\" >1968-01-28 21:50:00</td>\n",
+ " <td id=\"T_c1c6b_row7_col2\" class=\"data row7 col2\" >2883-1968-01-28-21-50-00</td>\n",
+ " <td id=\"T_c1c6b_row7_col3\" class=\"data row7 col3\" >4.712403</td>\n",
+ " <td id=\"T_c1c6b_row7_col4\" class=\"data row7 col4\" >nan</td>\n",
+ " <td id=\"T_c1c6b_row7_col5\" class=\"data row7 col5\" >8.257742</td>\n",
+ " <td id=\"T_c1c6b_row7_col6\" class=\"data row7 col6\" >8.257742</td>\n",
+ " <td id=\"T_c1c6b_row7_col7\" class=\"data row7 col7\" >nan</td>\n",
+ " <td id=\"T_c1c6b_row7_col8\" class=\"data row7 col8\" >8.257742</td>\n",
" </tr>\n",
" <tr>\n",
- " <th id=\"T_f5435_level0_row8\" class=\"row_heading level0 row8\" >8</th>\n",
- " <td id=\"T_f5435_row8_col0\" class=\"data row8 col0\" >657</td>\n",
- " <td id=\"T_f5435_row8_col1\" class=\"data row8 col1\" >1969-04-14 15:47:00</td>\n",
- " <td id=\"T_f5435_row8_col2\" class=\"data row8 col2\" >657-1969-04-14-15-47-00</td>\n",
- " <td id=\"T_f5435_row8_col3\" class=\"data row8 col3\" >nan</td>\n",
- " <td id=\"T_f5435_row8_col4\" class=\"data row8 col4\" >7.903614</td>\n",
- " <td id=\"T_f5435_row8_col5\" class=\"data row8 col5\" >nan</td>\n",
- " <td id=\"T_f5435_row8_col6\" class=\"data row8 col6\" >7.903614</td>\n",
+ " <th id=\"T_c1c6b_level0_row8\" class=\"row_heading level0 row8\" >8</th>\n",
+ " <td id=\"T_c1c6b_row8_col0\" class=\"data row8 col0\" >1515</td>\n",
+ " <td id=\"T_c1c6b_row8_col1\" class=\"data row8 col1\" >1968-07-18 08:28:00</td>\n",
+ " <td id=\"T_c1c6b_row8_col2\" class=\"data row8 col2\" >1515-1968-07-18-08-28-00</td>\n",
+ " <td id=\"T_c1c6b_row8_col3\" class=\"data row8 col3\" >3.112700</td>\n",
+ " <td id=\"T_c1c6b_row8_col4\" class=\"data row8 col4\" >3.684614</td>\n",
+ " <td id=\"T_c1c6b_row8_col5\" class=\"data row8 col5\" >8.654839</td>\n",
+ " <td id=\"T_c1c6b_row8_col6\" class=\"data row8 col6\" >8.654839</td>\n",
+ " <td id=\"T_c1c6b_row8_col7\" class=\"data row8 col7\" >3.104674</td>\n",
+ " <td id=\"T_c1c6b_row8_col8\" class=\"data row8 col8\" >2.907289</td>\n",
" </tr>\n",
" <tr>\n",
- " <th id=\"T_f5435_level0_row9\" class=\"row_heading level0 row9\" >9</th>\n",
- " <td id=\"T_f5435_row9_col0\" class=\"data row9 col0\" >7916</td>\n",
- " <td id=\"T_f5435_row9_col1\" class=\"data row9 col1\" >1968-12-20 03:38:00</td>\n",
- " <td id=\"T_f5435_row9_col2\" class=\"data row9 col2\" >7916-1968-12-20-03-38-00</td>\n",
- " <td id=\"T_f5435_row9_col3\" class=\"data row9 col3\" >3.901992</td>\n",
- " <td id=\"T_f5435_row9_col4\" class=\"data row9 col4\" >6.084523</td>\n",
- " <td id=\"T_f5435_row9_col5\" class=\"data row9 col5\" >4.318586</td>\n",
- " <td id=\"T_f5435_row9_col6\" class=\"data row9 col6\" >4.629502</td>\n",
+ " <th id=\"T_c1c6b_level0_row9\" class=\"row_heading level0 row9\" >9</th>\n",
+ " <td id=\"T_c1c6b_row9_col0\" class=\"data row9 col0\" >6754</td>\n",
+ " <td id=\"T_c1c6b_row9_col1\" class=\"data row9 col1\" >1968-09-21 01:27:00</td>\n",
+ " <td id=\"T_c1c6b_row9_col2\" class=\"data row9 col2\" >6754-1968-09-21-01-27-00</td>\n",
+ " <td id=\"T_c1c6b_row9_col3\" class=\"data row9 col3\" >5.082918</td>\n",
+ " <td id=\"T_c1c6b_row9_col4\" class=\"data row9 col4\" >3.102132</td>\n",
+ " <td id=\"T_c1c6b_row9_col5\" class=\"data row9 col5\" >2.346644</td>\n",
+ " <td id=\"T_c1c6b_row9_col6\" class=\"data row9 col6\" >9.657755</td>\n",
+ " <td id=\"T_c1c6b_row9_col7\" class=\"data row9 col7\" >2.324913</td>\n",
+ " <td id=\"T_c1c6b_row9_col8\" class=\"data row9 col8\" >2.346644</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n"
],
"text/plain": [
- "<pandas.io.formats.style.Styler at 0x1454ac370>"
+ "<pandas.io.formats.style.Styler at 0x1433ebd00>"
]
},
- "execution_count": 32,
+ "execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
@@ -496,7 +539,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.9.17"
+ "version": "3.10.13"
},
"orig_nbformat": 4,
"vscode": {
diff --git a/src/timeseriesflattener/feature_specs/group_specs.py b/src/timeseriesflattener/feature_specs/group_specs.py
index 88f1180..0735176 100644
--- a/src/timeseriesflattener/feature_specs/group_specs.py
+++ b/src/timeseriesflattener/feature_specs/group_specs.py
@@ -1,6 +1,6 @@
import itertools
from dataclasses import dataclass
-from typing import Dict, List, Sequence, Union
+from typing import Dict, List, Sequence, Tuple, Union
import pandas as pd
from timeseriesflattener.aggregation_fns import AggregationFunType
@@ -33,7 +33,7 @@ class PredictorGroupSpec(BaseModel):
# Shared attributes from GroupSpec
prefix: str = "pred"
- lookbehind_days: List[float]
+ lookbehind_days: List[Union[float, Tuple[float, float]]]
named_dataframes: Sequence[NamedDataframe]
aggregation_fns: Sequence[AggregationFunType]
fallback: Sequence[Union[int, float, str]]
@@ -79,7 +79,7 @@ class OutcomeGroupSpec(BaseModel):
fallback: Sequence[Union[int, float, str]]
# Individual attributes
- lookahead_days: List[float]
+ lookahead_days: List[Union[float, Tuple[float, float]]]
incident: Sequence[bool]
def create_combinations(self) -> List[OutcomeSpec]:
diff --git a/src/timeseriesflattener/feature_specs/single_specs.py b/src/timeseriesflattener/feature_specs/single_specs.py
index 467c4ed..5831f24 100644
--- a/src/timeseriesflattener/feature_specs/single_specs.py
+++ b/src/timeseriesflattener/feature_specs/single_specs.py
@@ -1,14 +1,26 @@
from dataclasses import dataclass
-from typing import Union
+from typing import Tuple, Union
import pandas as pd
from timeseriesflattener.aggregation_fns import AggregationFunType
from timeseriesflattener.utils.pydantic_basemodel import BaseModel
+@dataclass(frozen=True)
+class LookPeriod:
+ min_days: float
+ max_days: float
+
+ def __post_init__(self):
+ if self.min_days > self.max_days:
+ raise ValueError(
+ f"Invalid LookPeriod. The min_days ({self.min_days}) must be smaller than the max_days {self.max_days}.",
+ )
+
+
@dataclass(frozen=True)
class CoercedFloats:
- lookwindow: Union[float, int]
+ lookperiod: LookPeriod
fallback: Union[float, int]
@@ -20,17 +32,25 @@ def can_be_coerced_losslessly_to_int(value: float) -> bool:
return False
-def coerce_floats(lookwindow: float, fallback: float) -> CoercedFloats:
- lookwindow = (
- lookwindow
- if not can_be_coerced_losslessly_to_int(lookwindow)
- else int(lookwindow)
+def coerce_floats(lookperiod: LookPeriod, fallback: float) -> CoercedFloats:
+ min_days = (
+ lookperiod.min_days
+ if not can_be_coerced_losslessly_to_int(lookperiod.min_days)
+ else int(lookperiod.min_days)
)
+ max_days = (
+ lookperiod.max_days
+ if not can_be_coerced_losslessly_to_int(lookperiod.max_days)
+ else int(lookperiod.max_days)
+ )
+
+ coerced_lookperiod = LookPeriod(min_days=min_days, max_days=max_days)
+
fallback = (
fallback if not can_be_coerced_losslessly_to_int(fallback) else int(fallback)
)
- return CoercedFloats(lookwindow=lookwindow, fallback=fallback)
+ return CoercedFloats(lookperiod=coerced_lookperiod, fallback=fallback)
class StaticSpec(BaseModel):
@@ -59,13 +79,18 @@ class StaticSpec(BaseModel):
def get_temporal_col_name(
prefix: str,
feature_base_name: str,
- lookwindow: Union[float, int],
+ lookperiod: LookPeriod,
aggregation_fn: AggregationFunType,
fallback: Union[float, int],
) -> str:
"""Get the column name for the temporal feature."""
- coerced = coerce_floats(lookwindow=lookwindow, fallback=fallback)
- col_str = f"{prefix}_{feature_base_name}_within_{coerced.lookwindow!s}_days_{aggregation_fn.__name__}_fallback_{coerced.fallback}"
+ coerced = coerce_floats(lookperiod=lookperiod, fallback=fallback)
+ lookperiod_str = (
+ f"{coerced.lookperiod.max_days!s}"
+ if coerced.lookperiod.min_days == 0
+ else f"{coerced.lookperiod.min_days!s}_to_{coerced.lookperiod.max_days!s}"
+ )
+ col_str = f"{prefix}_{feature_base_name}_within_{lookperiod_str}_days_{aggregation_fn.__name__}_fallback_{coerced.fallback}"
return col_str
@@ -80,7 +105,8 @@ class OutcomeSpec(BaseModel):
NOTE: Column names can be overridden when initialising TimeSeriesFlattener.
feature_base_name: The name of the feature. Used for column name generation, e.g.
<prefix>_<feature_baase_name>_<metadata>.
- lookahead_days: How far ahead from the prediction time to look for outcome values.
+ lookahead_days: In which interval from the prediction time to look for outcome values.
+ Can be tuple of two floats specifying (min_days, max_days) or float | int which will resolve to (0, value).
aggregation_fn: How to aggregate multiple values within lookahead days. Should take a grouped dataframe as input and return a single value.
fallback: Value to return if no values is found within window.
incident: Whether the outcome is incident or not. E.g. type 2 diabetes is incident because you can only experience it once.
@@ -92,18 +118,27 @@ class OutcomeSpec(BaseModel):
timeseries_df: pd.DataFrame
feature_base_name: str
- lookahead_days: float
+ lookahead_days: Union[float, Tuple[float, float]]
aggregation_fn: AggregationFunType
fallback: Union[float, int]
incident: bool
prefix: str = "outc"
+ @property
+ def lookahead_period(self) -> LookPeriod:
+ if isinstance(self.lookahead_days, (float, int)):
+ return LookPeriod(min_days=0, max_days=self.lookahead_days)
+ return LookPeriod(
+ min_days=self.lookahead_days[0],
+ max_days=self.lookahead_days[1],
+ )
+
def get_output_col_name(self) -> str:
"""Get the column name for the output column."""
col_str = get_temporal_col_name(
prefix=self.prefix,
feature_base_name=self.feature_base_name,
- lookwindow=self.lookahead_days,
+ lookperiod=self.lookahead_period,
aggregation_fn=self.aggregation_fn,
fallback=self.fallback,
)
@@ -129,12 +164,10 @@ class PredictorSpec(BaseModel):
NOTE: Column names can be overridden when initialising TimeSeriesFlattener.
feature_base_name: The name of the feature. Used for column name generation, e.g.
<prefix>_<feature_baase_name>_<metadata>.
- lookbehind_days: How far behind from the prediction time to look for predictor values.
- aggregation_fn: How to aggregate multiple values within lookahead days. Should take a grouped dataframe as input and return a single value.
+ lookbehind_days: In which interval from the prediction time to look for predictor values.
+ Can be tuple of two floats specifying (min_days, max_days) or float | int which will resolve to (0, value).
+ aggregation_fn: How to aggregate multiple values within lookbehind days. Should take a grouped dataframe as input and return a single value.
fallback: Value to return if no values is found within window.
- incident: Whether the outcome is incident or not. E.g. type 2 diabetes is incident because you can only experience it once.
- Incident outcomes can be handled in a vectorised way during resolution, which is faster than non-incident outcomes.
- Requires that each entity only occurs once in the timeseries_df.
prefix: The prefix used for column name generation, e.g.
<prefix>_<feature_name>_<metadata>. Defaults to "pred".
"""
@@ -143,15 +176,24 @@ class PredictorSpec(BaseModel):
feature_base_name: str
aggregation_fn: AggregationFunType
fallback: Union[float, int]
- lookbehind_days: float
+ lookbehind_days: Union[float, Tuple[float, float]]
prefix: str = "pred"
+ @property
+ def lookbehind_period(self) -> LookPeriod:
+ if isinstance(self.lookbehind_days, (float, int)):
+ return LookPeriod(min_days=0, max_days=self.lookbehind_days)
+ return LookPeriod(
+ min_days=self.lookbehind_days[0],
+ max_days=self.lookbehind_days[1],
+ )
+
def get_output_col_name(self) -> str:
"""Generate the column name for the output column."""
return get_temporal_col_name(
prefix=self.prefix,
feature_base_name=self.feature_base_name,
- lookwindow=self.lookbehind_days,
+ lookperiod=self.lookbehind_period,
aggregation_fn=self.aggregation_fn,
fallback=self.fallback,
)
diff --git a/src/timeseriesflattener/flattened_dataset.py b/src/timeseriesflattener/flattened_dataset.py
index 7971e63..34e489e 100644
--- a/src/timeseriesflattener/flattened_dataset.py
+++ b/src/timeseriesflattener/flattened_dataset.py
@@ -20,6 +20,7 @@ from pydantic import BaseModel as PydanticBaseModel
from timeseriesflattener.feature_cache.abstract_feature_cache import FeatureCache
from timeseriesflattener.feature_specs.single_specs import (
AnySpec,
+ LookPeriod,
OutcomeSpec,
PredictorSpec,
StaticSpec,
@@ -257,7 +258,7 @@ class TimeseriesFlattener:
def _drop_records_outside_interval_days(
df: DataFrame,
direction: str,
- interval_days: float,
+ lookperiod: LookPeriod,
timestamp_pred_colname: str,
timestamp_value_colname: str,
) -> DataFrame:
@@ -267,7 +268,7 @@ class TimeseriesFlattener:
Args:
direction (str): Whether to look ahead or behind.
- interval_days (float): How far to look
+ lookperiod (LookPeriod): Interval to look within.
df (DataFrame): Source dataframe
timestamp_pred_colname (str): Name of timestamp column for predictions in df.
timestamp_value_colname (str): Name of timestamp column for values in df.
@@ -287,12 +288,12 @@ class TimeseriesFlattener:
if direction == "ahead":
df["is_in_interval"] = (
- df["time_from_pred_to_val_in_days"] <= interval_days
- ) & (df["time_from_pred_to_val_in_days"] > 0)
+ df["time_from_pred_to_val_in_days"] <= lookperiod.max_days
+ ) & (df["time_from_pred_to_val_in_days"] > lookperiod.min_days)
elif direction == "behind":
df["is_in_interval"] = (
- df["time_from_pred_to_val_in_days"] >= -interval_days
- ) & (df["time_from_pred_to_val_in_days"] < 0)
+ df["time_from_pred_to_val_in_days"] >= -lookperiod.max_days
+ ) & (df["time_from_pred_to_val_in_days"] < -lookperiod.min_days)
else:
raise ValueError("direction can only be 'ahead' or 'behind'")
@@ -349,17 +350,17 @@ class TimeseriesFlattener:
# Drop prediction times without event times within interval days
if isinstance(output_spec, OutcomeSpec):
direction = "ahead"
- interval_days = output_spec.lookahead_days
+ lookperiod = output_spec.lookahead_period
elif isinstance(output_spec, PredictorSpec):
direction = "behind"
- interval_days = output_spec.lookbehind_days
+ lookperiod = output_spec.lookbehind_period
else:
raise ValueError(f"Unknown output_spec type {type(output_spec)}")
df = TimeseriesFlattener._drop_records_outside_interval_days(
df,
direction=direction,
- interval_days=interval_days,
+ lookperiod=lookperiod,
timestamp_pred_colname=timestamp_pred_col_name,
timestamp_value_colname=timestamp_val_col_name,
)
@@ -658,8 +659,12 @@ class TimeseriesFlattener:
if outcome_spec.is_dichotomous():
outcome_is_within_lookahead = (
df[prediction_timestamp_col_name] # type: ignore
- + timedelta(days=outcome_spec.lookahead_days)
+ + timedelta(days=outcome_spec.lookahead_period.max_days)
> df[outcome_timestamp_col_name]
+ ) & (
+ df[prediction_timestamp_col_name] # type: ignore
+ + timedelta(days=outcome_spec.lookahead_period.min_days)
+ <= df[outcome_timestamp_col_name]
)
df[outcome_spec.get_output_col_name()] = outcome_is_within_lookahead.astype(
@@ -690,11 +695,11 @@ class TimeseriesFlattener:
if isinstance(spec, PredictorSpec):
min_val_date = spec.timeseries_df[self.timestamp_col_name].min() # type: ignore
- return min_val_date + pd.Timedelta(days=spec.lookbehind_days)
+ return min_val_date + pd.Timedelta(days=spec.lookbehind_period.max_days)
if isinstance(spec, OutcomeSpec):
max_val_date = spec.timeseries_df[self.timestamp_col_name].max() # type: ignore
- return max_val_date - pd.Timedelta(days=spec.lookahead_days)
+ return max_val_date - pd.Timedelta(days=spec.lookahead_period.max_days)
raise ValueError(f"Spec type {type(spec)} not recognised.")
|
Aarhus-Psychiatry-Research__timeseriesflattener-48
|
[
{
"changes": {
"added_entities": [
"src/timeseriesflattener/feature_spec_objects.py:PredictorSpec.get_cutoff_date",
"src/timeseriesflattener/feature_spec_objects.py:OutcomeSpec.get_cutoff_date"
],
"added_modules": null,
"edited_entities": [
"src/timeseriesflattener/feature_spec_objects.py:AnySpec.__init__",
"src/timeseriesflattener/feature_spec_objects.py:AnySpec.__eq__",
"src/timeseriesflattener/feature_spec_objects.py:TemporalSpec.__init__"
],
"edited_modules": [
"src/timeseriesflattener/feature_spec_objects.py:AnySpec",
"src/timeseriesflattener/feature_spec_objects.py:TemporalSpec",
"src/timeseriesflattener/feature_spec_objects.py:PredictorSpec",
"src/timeseriesflattener/feature_spec_objects.py:OutcomeSpec"
]
},
"file": "src/timeseriesflattener/feature_spec_objects.py"
},
{
"changes": {
"added_entities": [
"src/timeseriesflattener/flattened_dataset.py:SpecCollection.__len__",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._add_temporal_batch",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._add_static_info",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._process_static_specs",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._drop_pred_time_if_insufficient_look_distance",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._process_temporal_specs",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._check_that_spec_df_has_required_columns",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_spec",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_age",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.compute"
],
"added_modules": [
"src/timeseriesflattener/flattened_dataset.py:SpecCollection"
],
"edited_entities": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._override_cache_attributes_with_self_attributes",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.__init__",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._flatten_temporal_values_to_df",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._add_back_prediction_times_without_value",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._resolve_multiple_values_within_interval_days",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._drop_records_outside_interval_days",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._get_temporal_feature",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_temporal_predictor_batch",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_age_and_birth_year",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_static_info",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._add_temporal_col_to_flattened_dataset",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_temporal_outcome",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_temporal_predictor",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.get_df"
],
"edited_modules": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener"
]
},
"file": "src/timeseriesflattener/flattened_dataset.py"
},
{
"changes": {
"added_entities": [
"src/timeseriesflattener/utils.py:print_df_dimensions_diff"
],
"added_modules": [
"src/timeseriesflattener/utils.py:print_df_dimensions_diff"
],
"edited_entities": null,
"edited_modules": null
},
"file": "src/timeseriesflattener/utils.py"
}
] |
Aarhus-Psychiatry-Research/timeseriesflattener
|
35831b493805d0c33ad447d8a8d8f868e77f8d68
|
feat: drop if insufficient lookbehind or lookahead
Based on min in values_df?
Should be based on max in values_df.
1. Refactor to collect all specs before adding
2. Have one shared mechanism of adding specs, and allow it to take a list or a single spec at a time
3. Get the latest required date for sufficient lookbehind (get min from all PredSpec values_df's, then get max of that)
4. Get the earliest required date for sufficient lookahead (get max from all OutcomeSpec values_df's, then get min of that)
5. Drop based on required dates
|
diff --git a/src/timeseriesflattener/feature_spec_objects.py b/src/timeseriesflattener/feature_spec_objects.py
index c010b0a..c4a3e81 100644
--- a/src/timeseriesflattener/feature_spec_objects.py
+++ b/src/timeseriesflattener/feature_spec_objects.py
@@ -135,8 +135,17 @@ class AnySpec(BaseModel):
def __init__(self, **kwargs: Any):
kwargs = resolve_values_df(kwargs)
+ # Check that required columns exist
check_that_col_names_in_kwargs_exist_in_df(kwargs, df=kwargs["values_df"])
+ if (
+ "input_col_name_override" not in kwargs
+ and "value" not in kwargs["values_df"].columns
+ ):
+ raise KeyError(
+ f"The values_df must have a column named 'value' or an input_col_name_override must be specified. Columns in values_df: {list(kwargs['values_df'].columns)}",
+ )
+
if in_dict_and_not_none(d=kwargs, key="output_col_name_override"):
# If an output_col_name_override is specified, don't prepend a prefix to it
kwargs["prefix"] = ""
@@ -159,11 +168,14 @@ class AnySpec(BaseModel):
Trying to run `spec in list_of_specs` works for all attributes except for df, since the truth value of a dataframe is ambiguous.
To remedy this, we use pandas' .equals() method for comparing the dfs, and get the combined truth value.
"""
- other_attributes_equal = all(
- getattr(self, attr) == getattr(other, attr)
- for attr in self.__dict__
- if attr != "values_df"
- )
+ try:
+ other_attributes_equal = all(
+ getattr(self, attr) == getattr(other, attr)
+ for attr in self.__dict__
+ if attr != "values_df"
+ )
+ except AttributeError:
+ return False
dfs_equal = self.values_df.equals(other.values_df) # type: ignore
@@ -218,6 +230,25 @@ class TemporalSpec(AnySpec):
super().__init__(**data)
+ timestamp_col_type = self.values_df[self.timestamp_col_name].dtype # type: ignore
+
+ if timestamp_col_type not in ("Timestamp", "datetime64[ns]"):
+ # Convert column dtype to datetime64[ns] if it isn't already
+ log.info(
+ f"{self.feature_name}: Converting timestamp column to datetime64[ns]",
+ )
+
+ self.values_df[self.timestamp_col_name] = pd.to_datetime(
+ self.values_df[self.timestamp_col_name],
+ )
+
+ min_timestamp = min(self.values_df[self.timestamp_col_name])
+
+ if min_timestamp < pd.Timestamp("1971-01-01"):
+ log.warning(
+ f"{self.feature_name}: Minimum timestamp is {min_timestamp} - perhaps ints were coerced to timestamps?",
+ )
+
self.resolve_multiple_fn = data["resolve_multiple_fn"]
# override fallback strings with objects
@@ -249,6 +280,20 @@ class PredictorSpec(TemporalSpec):
super().__init__(**data)
+ def get_cutoff_date(self) -> pd.Timestamp:
+ """Get the cutoff date from a spec.
+
+ A cutoff date is the earliest date that a prediction time can get data from the values_df.
+ We do not want to include those prediction times, as we might make incorrect inferences.
+ For example, if a spec says to look 5 years into the future, but we only have one year of data,
+ there will necessarily be fewer outcomes - without that reflecting reality. This means our model won't generalise.
+
+ Returns:
+ pd.Timestamp: A cutoff date.
+ """
+ min_val_date = self.values_df[self.timestamp_col_name].min() # type: ignore
+ return min_val_date + pd.Timedelta(days=self.lookbehind_days)
+
class OutcomeSpec(TemporalSpec):
"""Specification for a single predictor, where the df has been resolved."""
@@ -290,6 +335,21 @@ class OutcomeSpec(TemporalSpec):
return len(self.values_df[col_name].unique()) <= 2 # type: ignore
+ def get_cutoff_date(self) -> pd.Timestamp:
+ """Get the cutoff date from a spec.
+
+ A cutoff date is the earliest date that a prediction time can get data from the values_df.
+ We do not want to include those prediction times, as we might make incorrect inferences.
+ For example, if a spec says to look 5 years into the future, but we only have one year of data,
+ there will necessarily be fewer outcomes - without that reflecting reality. This means our model won't generalise.
+
+ Returns:
+ pd.Timestamp: A cutoff date.
+ """
+ max_val_date = self.values_df[self.timestamp_col_name].max() # type: ignore
+
+ return max_val_date - pd.Timedelta(days=self.lookahead_days)
+
class MinGroupSpec(BaseModel):
"""Minimum specification for a group of features, whether they're looking
diff --git a/src/timeseriesflattener/flattened_dataset.py b/src/timeseriesflattener/flattened_dataset.py
index 42a1d86..555a731 100644
--- a/src/timeseriesflattener/flattened_dataset.py
+++ b/src/timeseriesflattener/flattened_dataset.py
@@ -10,7 +10,7 @@ import time
from collections.abc import Callable
from datetime import timedelta
from multiprocessing import Pool
-from typing import Optional
+from typing import Optional, Union
import coloredlogs
import numpy as np
@@ -19,22 +19,38 @@ import tqdm
from catalogue import Registry # noqa # pylint: disable=unused-import
from dask.diagnostics import ProgressBar
from pandas import DataFrame
+from pydantic import BaseModel as PydanticBaseModel
from timeseriesflattener.feature_cache.abstract_feature_cache import FeatureCache
from timeseriesflattener.feature_spec_objects import (
AnySpec,
OutcomeSpec,
PredictorSpec,
+ StaticSpec,
TemporalSpec,
)
from timeseriesflattener.flattened_ds_validator import ValidateInitFlattenedDataset
from timeseriesflattener.resolve_multiple_functions import resolve_multiple_fns
+from timeseriesflattener.utils import print_df_dimensions_diff
ProgressBar().register()
log = logging.getLogger(__name__)
+class SpecCollection(PydanticBaseModel):
+ """A collection of specs."""
+
+ outcome_specs: list[OutcomeSpec] = []
+ predictor_specs: list[PredictorSpec] = []
+ static_specs: list[AnySpec] = []
+
+ def __len__(self):
+ return (
+ len(self.outcome_specs) + len(self.predictor_specs) + len(self.static_specs)
+ )
+
+
class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
"""Turn a set of time-series into tabular prediction-time data."""
@@ -46,6 +62,9 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
Avoids duplicate specification.
"""
+ if self.cache is None:
+ raise ValueError("Cache is None, cannot override attributes")
+
if (
not hasattr(self.cache, "prediction_times_df")
or self.cache.prediction_times_df is None
@@ -57,7 +76,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
)
self.cache.prediction_times_df = prediction_times_df
- for attr in ["pred_time_uuid_col_name", "timestamp_col_name", "id_col_name"]:
+ for attr in ("pred_time_uuid_col_name", "timestamp_col_name", "id_col_name"):
if hasattr(self.cache, attr) and getattr(self.cache, attr) is not None:
if getattr(self.cache, attr) != getattr(self, attr):
log.warning(
@@ -68,13 +87,14 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
def __init__( # pylint: disable=too-many-arguments
self,
prediction_times_df: DataFrame,
+ drop_pred_times_with_insufficient_look_distance: bool, # noqa
cache: Optional[FeatureCache] = None,
id_col_name: str = "dw_ek_borger",
timestamp_col_name: str = "timestamp",
predictor_col_name_prefix: str = "pred",
outcome_col_name_prefix: str = "outc",
n_workers: int = 60,
- log_to_stdout: bool = True,
+ log_to_stdout: bool = True, # noqa
):
"""Class containing a time-series, flattened.
@@ -108,6 +128,10 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
outcome_col_name_prefix (str, optional): Prefix for outcome col names. Defaults to "outc_".
n_workers (int): Number of subprocesses to spawn for parallelization. Defaults to 60.
log_to_stdout (bool): Whether to log to stdout. Either way, also logs to the __name__ namespace, which you can capture with a root logger. Defaults to True.
+ drop_pred_times_with_insufficient_look_distance (bool): Whether to drop prediction times with insufficient look distance.
+ For example, say your feature has a lookbehind of 2 years, and your first datapoint is 2013-01-01.
+ The first prediction time that has sufficient look distance will be on 2015-01-1.
+ Otherwise, your feature will imply that you've looked two years into the past, even though you have less than two years of data to look at.
Raises:
ValueError: If timestamp_col_name or id_col_name is not in prediction_times_df
@@ -121,6 +145,10 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
self.outcome_col_name_prefix = outcome_col_name_prefix
self.pred_time_uuid_col_name = "prediction_time_uuid"
self.cache = cache
+ self.unprocessed_specs: SpecCollection = SpecCollection()
+ self.drop_pred_times_with_insufficient_look_distance = (
+ drop_pred_times_with_insufficient_look_distance
+ )
if self.cache:
self._override_cache_attributes_with_self_attributes(prediction_times_df)
@@ -152,12 +180,125 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
fmt="%(asctime)s [%(levelname)s] %(message)s",
)
+ @staticmethod
+ def _add_back_prediction_times_without_value(
+ df: DataFrame,
+ pred_times_with_uuid: DataFrame,
+ pred_time_uuid_colname: str,
+ ) -> DataFrame:
+ """Ensure all prediction times are represented in the returned
+
+ dataframe.
+
+ Args:
+ df (DataFrame): Dataframe with prediction times but without uuid.
+ pred_times_with_uuid (DataFrame): Dataframe with prediction times and uuid.
+ pred_time_uuid_colname (str): Name of uuid column in both df and pred_times_with_uuid.
+
+ Returns:
+ DataFrame: A merged dataframe with all prediction times.
+ """
+ return pd.merge(
+ pred_times_with_uuid,
+ df,
+ how="left",
+ on=pred_time_uuid_colname,
+ suffixes=("", "_temp"),
+ ).drop(["timestamp_pred"], axis=1)
+
+ @staticmethod
+ def _resolve_multiple_values_within_interval_days(
+ resolve_multiple: Callable,
+ df: DataFrame,
+ pred_time_uuid_colname: str,
+ ) -> DataFrame:
+ """Apply the resolve_multiple function to prediction_times where there
+
+ are multiple values within the interval_days lookahead.
+
+ Args:
+ resolve_multiple (Callable): Takes a grouped df and collapses each group to one record (e.g. sum, count etc.).
+ df (DataFrame): Source dataframe with all prediction time x val combinations.
+ pred_time_uuid_colname (str): Name of uuid column in df.
+
+ Returns:
+ DataFrame: DataFrame with one row pr. prediction time.
+ """
+ # Convert timestamp val to numeric that can be used for resolve_multiple functions
+ # Numeric value amounts to days passed since 1/1/1970
+ try:
+ df["timestamp_val"] = (
+ df["timestamp_val"] - dt.datetime(1970, 1, 1)
+ ).dt.total_seconds() / 86400
+ except TypeError:
+ log.info("All values are NaT, returning empty dataframe")
+
+ # Sort by timestamp_pred in case resolve_multiple needs dates
+ df = df.sort_values(by="timestamp_val").groupby(pred_time_uuid_colname)
+
+ if isinstance(resolve_multiple, str):
+ resolve_multiple = resolve_multiple_fns.get(resolve_multiple)
+
+ if callable(resolve_multiple):
+ df = resolve_multiple(df).reset_index()
+ else:
+ raise ValueError("resolve_multiple must be or resolve to a Callable")
+
+ return df
+
+ @staticmethod
+ def _drop_records_outside_interval_days(
+ df: DataFrame,
+ direction: str,
+ interval_days: float,
+ timestamp_pred_colname: str,
+ timestamp_value_colname: str,
+ ) -> DataFrame:
+ """Filter by time from from predictions to values.
+
+ Drop if distance from timestamp_pred to timestamp_value is outside interval_days. Looks in `direction`.
+
+ Args:
+ direction (str): Whether to look ahead or behind.
+ interval_days (float): How far to look
+ df (DataFrame): Source dataframe
+ timestamp_pred_colname (str): Name of timestamp column for predictions in df.
+ timestamp_value_colname (str): Name of timestamp column for values in df.
+
+ Raises:
+ ValueError: If direction is niether ahead nor behind.
+
+ Returns:
+ DataFrame
+ """
+ df["time_from_pred_to_val_in_days"] = (
+ (df[timestamp_value_colname] - df[timestamp_pred_colname])
+ / (np.timedelta64(1, "s"))
+ / 86_400
+ )
+ # Divide by 86.400 seconds/day
+
+ if direction == "ahead":
+ df["is_in_interval"] = (
+ df["time_from_pred_to_val_in_days"] <= interval_days
+ ) & (df["time_from_pred_to_val_in_days"] > 0)
+ elif direction == "behind":
+ df["is_in_interval"] = (
+ df["time_from_pred_to_val_in_days"] >= -interval_days
+ ) & (df["time_from_pred_to_val_in_days"] < 0)
+ else:
+ raise ValueError("direction can only be 'ahead' or 'behind'")
+
+ return df[df["is_in_interval"]].drop(
+ ["is_in_interval", "time_from_pred_to_val_in_days"],
+ axis=1,
+ )
+
@staticmethod
def _flatten_temporal_values_to_df( # noqa pylint: disable=too-many-locals
prediction_times_with_uuid_df: DataFrame,
output_spec: AnySpec,
id_col_name: str,
- timestamp_col_name: str,
pred_time_uuid_col_name: str,
verbose: bool = False, # noqa
) -> DataFrame:
@@ -182,12 +323,6 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
Returns:
DataFrame
"""
- for col_name in (timestamp_col_name, id_col_name):
- if col_name not in output_spec.values_df.columns: # type: ignore
- raise ValueError(
- f"{col_name} does not exist in df_prediction_times, change the df or set another argument",
- )
-
# Generate df with one row for each prediction time x event time combination
# Drop dw_ek_borger for faster merge
df = pd.merge(
@@ -278,7 +413,6 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
]
],
id_col_name=self.id_col_name,
- timestamp_col_name=self.timestamp_col_name,
pred_time_uuid_col_name=self.pred_time_uuid_col_name,
output_spec=feature_spec,
)
@@ -351,84 +485,31 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
log.info("Merging with original df")
self._df = self._df.merge(right=new_features, on=self.pred_time_uuid_col_name)
- def add_temporal_predictor_batch( # pylint: disable=too-many-branches
+ def _add_temporal_batch( # pylint: disable=too-many-branches
self,
- predictor_batch: list[PredictorSpec],
+ temporal_batch: list[TemporalSpec],
):
"""Add predictors to the flattened dataframe from a list."""
# Shuffle predictor specs to avoid IO contention
- random.shuffle(predictor_batch)
+ random.shuffle(temporal_batch)
+
+ n_workers = min(self.n_workers, len(temporal_batch))
- with Pool(self.n_workers) as p:
+ with Pool(n_workers) as p:
flattened_predictor_dfs = list(
tqdm.tqdm(
- p.imap(func=self._get_temporal_feature, iterable=predictor_batch),
- total=len(predictor_batch),
+ p.imap(func=self._get_temporal_feature, iterable=temporal_batch),
+ total=len(temporal_batch),
),
)
- log.info("Feature generation complete, concatenating")
+ log.info("Processing complete, concatenating")
self._concatenate_flattened_timeseries(
flattened_predictor_dfs=flattened_predictor_dfs,
)
- def add_age_and_birth_year(
- self,
- id2date_of_birth: DataFrame,
- input_date_of_birth_col_name: Optional[str] = "date_of_birth",
- output_prefix: str = "pred",
- birth_year_as_predictor: bool = False, # noqa
- ):
- """Add age at prediction time as predictor.
-
- Also add patient's birth date. Has its own function because of its very frequent use.
-
- Args:
- id2date_of_birth (DataFrame): Two columns, id and date_of_birth.
- input_date_of_birth_col_name (str, optional): Name of the date_of_birth column in id2date_of_birth.
- Defaults to "date_of_birth".
- output_prefix (str, optional): Prefix for the output column. Defaults to "pred".
- birth_year_as_predictor (bool, optional): Whether to add birth year as a predictor. Defaults to False.
- """
- if id2date_of_birth[input_date_of_birth_col_name].dtype != "<M8[ns]":
- try:
- id2date_of_birth[input_date_of_birth_col_name] = pd.to_datetime(
- id2date_of_birth[input_date_of_birth_col_name],
- format="%Y-%m-%d",
- )
- except ValueError as e:
- raise ValueError(
- f"Conversion of {input_date_of_birth_col_name} to datetime failed, doesn't match format %Y-%m-%d. Recommend converting to datetime before adding.",
- ) from e
-
- output_age_col_name = f"{output_prefix}_age_in_years"
-
- self.add_static_info(
- static_spec=AnySpec(
- values_df=id2date_of_birth,
- input_col_name_override=input_date_of_birth_col_name,
- prefix=output_prefix,
- # We typically don't want to use date of birth as a predictor,
- # but might want to use transformations - e.g. "year of birth" or "age at prediction time".
- feature_name=input_date_of_birth_col_name,
- ),
- )
-
- data_of_birth_col_name = f"{output_prefix}_{input_date_of_birth_col_name}"
-
- self._df[output_age_col_name] = (
- (
- self._df[self.timestamp_col_name] - self._df[data_of_birth_col_name]
- ).dt.days
- / (365.25)
- ).round(2)
-
- if birth_year_as_predictor:
- # Convert datetime to year
- self._df["pred_birth_year"] = self._df[data_of_birth_col_name].dt.year
-
- def add_static_info(
+ def _add_static_info(
self,
static_spec: AnySpec,
):
@@ -482,6 +563,15 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
validate="m:1",
)
+ def _process_static_specs(self):
+ """Process static specs."""
+ for spec in self.unprocessed_specs.static_specs:
+ self._add_static_info(
+ static_spec=spec,
+ )
+
+ self.unprocessed_specs.static_specs.remove(spec)
+
def _add_incident_outcome(
self,
outcome_spec: OutcomeSpec,
@@ -526,196 +616,189 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
self._df = df
- def _add_temporal_col_to_flattened_dataset(
- self,
- output_spec: AnySpec,
- ):
- """Add a column to the dataset.
+ @print_df_dimensions_diff
+ def _drop_pred_time_if_insufficient_look_distance(self, df: pd.DataFrame):
+ """Drop prediction times if there is insufficient look distance.
- Either predictor or outcome depending on the type of specification.
+ A prediction time has insufficient look distance if the feature spec
+ tries to look beyond the boundary of the data.
+ For example, if a predictor specifies two years of lookbehind,
+ but you only have one year of data prior to the prediction time.
- Args:
- output_spec (Union[OutcomeSpec, PredictorSpec]): Specification of the output column.
+ Takes a dataframe as input to conform to a standard filtering interface,
+ which we can easily decorate.
"""
- timestamp_col_type = output_spec.values_df[self.timestamp_col_name].dtype # type: ignore
+ spec_batch = (
+ self.unprocessed_specs.outcome_specs
+ + self.unprocessed_specs.predictor_specs
+ )
- if timestamp_col_type not in ("Timestamp", "datetime64[ns]"):
- # Convert dtype to timestamp
- raise ValueError(
- f"{self.timestamp_col_name} is of type {timestamp_col_type}, not 'Timestamp' from Pandas. Will cause problems. Convert before initialising FlattenedDataset.",
- )
+ # Find the latest cutoff date for predictors
+ cutoff_date_behind = pd.Timestamp("1700-01-01")
- df = TimeseriesFlattener._flatten_temporal_values_to_df(
- prediction_times_with_uuid_df=self._df[
- [
- self.id_col_name,
- self.timestamp_col_name,
- self.pred_time_uuid_col_name,
- ]
- ],
- output_spec=output_spec,
- id_col_name=self.id_col_name,
- timestamp_col_name=self.timestamp_col_name,
- pred_time_uuid_col_name=self.pred_time_uuid_col_name,
- )
+ # Find the earliest cutoff date for outcomes
+ cutoff_date_ahead = pd.Timestamp("2200-01-01")
- self._df = self._df.merge(
- right=df,
- on=self.pred_time_uuid_col_name,
- validate="1:1",
- )
+ for spec in spec_batch:
+ spec_cutoff_date = spec.get_cutoff_date()
- def add_temporal_outcome(
- self,
- output_spec: OutcomeSpec,
- ):
- """Add an outcome-column to the dataset.
+ if isinstance(spec, OutcomeSpec):
+ cutoff_date_ahead = min(cutoff_date_ahead, spec_cutoff_date)
+ elif isinstance(spec, PredictorSpec):
+ cutoff_date_behind = max(cutoff_date_behind, spec_cutoff_date)
- Args:
- output_spec (OutcomeSpec): OutcomeSpec object.
- """
+ # Drop all prediction times that are outside the cutoffs window
+ output_df = df[
+ (df[self.timestamp_col_name] >= cutoff_date_behind)
+ & (df[self.timestamp_col_name] <= cutoff_date_ahead)
+ ]
- if output_spec.incident:
- self._add_incident_outcome(
- outcome_spec=output_spec,
+ if output_df.shape[0] == 0:
+ raise ValueError(
+ "No records left after dropping records outside look distance",
)
- else:
- self._add_temporal_col_to_flattened_dataset(
- output_spec=output_spec,
- )
+ return output_df
- def add_temporal_predictor(
- self,
- output_spec: PredictorSpec,
- ):
- """Add a column with predictor values to the flattened dataset.
+ def _process_temporal_specs(self):
+ """Process outcome specs."""
- Args:
- output_spec (Union[PredictorSpec]): Specification of the output column.
- """
- self._add_temporal_col_to_flattened_dataset(
- output_spec=output_spec,
- )
+ for spec in self.unprocessed_specs.outcome_specs:
+ # Handle incident specs separately, since their operations can be vectorised,
+ # making them much faster
+ if spec.incident:
+ self._add_incident_outcome(
+ outcome_spec=spec,
+ )
- @staticmethod
- def _add_back_prediction_times_without_value(
- df: DataFrame,
- pred_times_with_uuid: DataFrame,
- pred_time_uuid_colname: str,
- ) -> DataFrame:
- """Ensure all prediction times are represented in the returned
+ self.unprocessed_specs.outcome_specs.remove(spec)
- dataframe.
+ temporal_batch = self.unprocessed_specs.outcome_specs
+ temporal_batch += self.unprocessed_specs.predictor_specs
- Args:
- df (DataFrame): Dataframe with prediction times but without uuid.
- pred_times_with_uuid (DataFrame): Dataframe with prediction times and uuid.
- pred_time_uuid_colname (str): Name of uuid column in both df and pred_times_with_uuid.
+ if self.drop_pred_times_with_insufficient_look_distance:
+ self._df = self._drop_pred_time_if_insufficient_look_distance(df=self._df)
- Returns:
- DataFrame: A merged dataframe with all prediction times.
- """
- return pd.merge(
- pred_times_with_uuid,
- df,
- how="left",
- on=pred_time_uuid_colname,
- suffixes=("", "_temp"),
- ).drop(["timestamp_pred"], axis=1)
+ if len(temporal_batch) > 0:
+ self._add_temporal_batch(temporal_batch=temporal_batch)
- @staticmethod
- def _resolve_multiple_values_within_interval_days(
- resolve_multiple: Callable,
- df: DataFrame,
- pred_time_uuid_colname: str,
- ) -> DataFrame:
- """Apply the resolve_multiple function to prediction_times where there
+ def _check_that_spec_df_has_required_columns(self, spec: AnySpec):
+ """Check that df has required columns."""
+ # Find all attributes in self that contain col_name
+ required_columns = [self.id_col_name]
- are multiple values within the interval_days lookahead.
+ if not isinstance(spec, StaticSpec):
+ required_columns += [self.timestamp_col_name]
- Args:
- resolve_multiple (Callable): Takes a grouped df and collapses each group to one record (e.g. sum, count etc.).
- df (DataFrame): Source dataframe with all prediction time x val combinations.
- pred_time_uuid_colname (str): Name of uuid column in df.
+ for col in required_columns:
+ if col not in spec.values_df.columns: # type: ignore
+ raise ValueError(f"Missing required column: {col}")
- Returns:
- DataFrame: DataFrame with one row pr. prediction time.
+ def add_spec(
+ self,
+ spec: Union[list[AnySpec], AnySpec],
+ ):
+ """Add a specification to the flattened dataset.
+
+ This adds it to a queue of unprocessed specs, which are not processed
+ until you call the .compute() or .get_df() methods. This allows us to
+ more effectiely parallelise the processing of the specs.
+
+ Most of the complexity lies in the OutcomeSpec and PredictorSpec objects.
+ For further documentation, see those objects and the tutorial.
"""
- # Convert timestamp val to numeric that can be used for resolve_multiple functions
- # Numeric value amounts to days passed since 1/1/1970
- try:
- df["timestamp_val"] = (
- df["timestamp_val"] - dt.datetime(1970, 1, 1)
- ).dt.total_seconds() / 86400
- except TypeError:
- log.info("All values are NaT, returning empty dataframe")
+ if isinstance(spec, AnySpec):
+ specs_to_process: list[AnySpec] = [spec]
+ else:
+ specs_to_process = spec
- # Sort by timestamp_pred in case resolve_multiple needs dates
- df = df.sort_values(by="timestamp_val").groupby(pred_time_uuid_colname)
+ for spec_i in specs_to_process:
+ allowed_spec_types = (OutcomeSpec, PredictorSpec, StaticSpec)
- if isinstance(resolve_multiple, str):
- resolve_multiple = resolve_multiple_fns.get(resolve_multiple)
+ if not isinstance(spec_i, allowed_spec_types):
+ raise ValueError(
+ f"Input is not allowed. Must be one of: {allowed_spec_types}",
+ )
- if callable(resolve_multiple):
- df = resolve_multiple(df).reset_index()
- else:
- raise ValueError("resolve_multiple must be or resolve to a Callable")
+ self._check_that_spec_df_has_required_columns(spec=spec_i)
- return df
+ if isinstance(spec_i, OutcomeSpec):
+ self.unprocessed_specs.outcome_specs.append(spec_i)
+ elif isinstance(spec_i, PredictorSpec):
+ self.unprocessed_specs.predictor_specs.append(spec_i)
+ elif isinstance(spec_i, StaticSpec):
+ self.unprocessed_specs.static_specs.append(spec_i)
- @staticmethod
- def _drop_records_outside_interval_days(
- df: DataFrame,
- direction: str,
- interval_days: float,
- timestamp_pred_colname: str,
- timestamp_value_colname: str,
- ) -> DataFrame:
- """Keep only rows where timestamp_value is within interval_days in
+ def add_age(
+ self,
+ date_of_birth_df: DataFrame,
+ date_of_birth_col_name: Optional[str] = "date_of_birth",
+ output_prefix: str = "pred",
+ ):
+ """Add age at prediction time as predictor.
- direction of timestamp_pred.
+ Has its own function because of its very frequent use.
Args:
- direction (str): Whether to look ahead or behind.
- interval_days (float): How far to look
- df (DataFrame): Source dataframe
- timestamp_pred_colname (str): Name of timestamp column for predictions in df.
- timestamp_value_colname (str): Name of timestamp column for values in df.
+ date_of_birth_df (DataFrame): Two columns, one matching self.id_col_name and one containing date_of_birth.
+ date_of_birth_col_name (str, optional): Name of the date_of_birth column in date_of_birth_df.
+ Defaults to "date_of_birth".
+ output_prefix (str, optional): Prefix for the output column. Defaults to "pred".
+ """
+ if date_of_birth_df[date_of_birth_col_name].dtype != "<M8[ns]":
+ try:
+ date_of_birth_df[date_of_birth_col_name] = pd.to_datetime(
+ date_of_birth_df[date_of_birth_col_name],
+ format="%Y-%m-%d",
+ )
+ except ValueError as e:
+ raise ValueError(
+ f"Conversion of {date_of_birth_col_name} to datetime failed, doesn't match format %Y-%m-%d. Recommend converting to datetime before adding.",
+ ) from e
- Raises:
- ValueError: If direction is niether ahead nor behind.
+ output_age_col_name = f"{output_prefix}_age_in_years"
- Returns:
- DataFrame
- """
- df["time_from_pred_to_val_in_days"] = (
- (df[timestamp_value_colname] - df[timestamp_pred_colname])
- / (np.timedelta64(1, "s"))
- / 86_400
+ self._add_static_info(
+ static_spec=AnySpec(
+ values_df=date_of_birth_df,
+ input_col_name_override=date_of_birth_col_name,
+ prefix="temp",
+ # We typically don't want to use date of birth as a predictor,
+ # but might want to use transformations - e.g. "year of birth" or "age at prediction time".
+ feature_name=date_of_birth_col_name,
+ ),
)
- # Divide by 86.400 seconds/day
- if direction == "ahead":
- df["is_in_interval"] = (
- df["time_from_pred_to_val_in_days"] <= interval_days
- ) & (df["time_from_pred_to_val_in_days"] > 0)
- elif direction == "behind":
- df["is_in_interval"] = (
- df["time_from_pred_to_val_in_days"] >= -interval_days
- ) & (df["time_from_pred_to_val_in_days"] < 0)
- else:
- raise ValueError("direction can only be 'ahead' or 'behind'")
+ tmp_date_of_birth_col_name = f"temp_{date_of_birth_col_name}"
- return df[df["is_in_interval"]].drop(
- ["is_in_interval", "time_from_pred_to_val_in_days"],
- axis=1,
- )
+ self._df[output_age_col_name] = (
+ (
+ self._df[self.timestamp_col_name] - self._df[tmp_date_of_birth_col_name]
+ ).dt.days
+ / (365.25)
+ ).round(2)
+
+ # Remove date of birth column
+ self._df.drop(columns=tmp_date_of_birth_col_name, inplace=True)
+
+ def compute(self):
+ """Compute the flattened dataset."""
+ if len(self.unprocessed_specs) == 0:
+ log.warning("No unprocessed specs, skipping")
+ return
+
+ self._process_temporal_specs()
+ self._process_static_specs()
def get_df(self) -> DataFrame:
- """Get the flattened dataframe.
+ """Get the flattened dataframe. Computes if any unprocessed specs are present.
Returns:
DataFrame: Flattened dataframe.
"""
+ if len(self.unprocessed_specs) > 0:
+ log.info("There were unprocessed specs, computing...")
+ self.compute()
+
+ # Process
return self._df
diff --git a/src/timeseriesflattener/utils.py b/src/timeseriesflattener/utils.py
index ed98fdf..a602b18 100644
--- a/src/timeseriesflattener/utils.py
+++ b/src/timeseriesflattener/utils.py
@@ -3,8 +3,10 @@
utilities. If this file grows, consider splitting it up.
"""
+import functools
+import logging
import os
-from collections.abc import Hashable
+from collections.abc import Callable, Hashable
from pathlib import Path
from typing import Any, Optional
@@ -18,6 +20,7 @@ PROJECT_ROOT = Path(__file__).resolve().parents[2]
def format_dict_for_printing(d: dict) -> str:
"""Format a dictionary for printing. Removes extra apostrophes, formats
+
colon to dashes, separates items with underscores and removes curly
brackets.
@@ -155,3 +158,57 @@ def assert_no_duplicate_dicts_in_list(predictor_spec_list: list[dict[str, Any]])
if len(duplicates) > 0:
raise ValueError(f"Found duplicates in list of dicts: {duplicates}")
+
+
+def print_df_dimensions_diff(
+ func: Callable,
+ print_when_starting: bool = False,
+ print_when_no_diff=False,
+):
+ """Print the difference in rows between the input and output dataframes."""
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ log = logging.getLogger(__name__)
+
+ if print_when_starting:
+ log.info(f"{func.__name__}: Starting")
+
+ arg_dfs = [arg for arg in args if isinstance(arg, pd.DataFrame)]
+ kwargs_dfs = [arg for arg in kwargs.values() if isinstance(arg, pd.DataFrame)]
+ potential_dfs = arg_dfs + kwargs_dfs
+
+ if len(potential_dfs) > 1:
+ raise ValueError("More than one DataFrame found in args or kwargs")
+
+ df = potential_dfs[0]
+
+ for dim in ("rows", "columns"):
+ dim_int = 0 if dim == "rows" else 1
+
+ n_in_dim_before_func = df.shape[dim_int]
+
+ if print_when_no_diff:
+ log.info(
+ f"{func.__name__}: {n_in_dim_before_func} {dim} before function",
+ )
+
+ result = func(*args, **kwargs)
+
+ diff = n_in_dim_before_func - result.shape[dim_int]
+
+ if diff != 0:
+ percent_diff = round(
+ (n_in_dim_before_func - result.shape[dim_int])
+ / n_in_dim_before_func,
+ 2,
+ )
+
+ log.info(f"{func.__name__}: Dropped {diff} ({percent_diff}%) {dim}")
+ else:
+ if print_when_no_diff:
+ log.info(f"{func.__name__}: No {dim} dropped")
+
+ return result
+
+ return wrapper
diff --git a/tutorials/01_basic.ipynb b/tutorials/01_basic.ipynb
index 83f0e71..07bcb84 100644
--- a/tutorials/01_basic.ipynb
+++ b/tutorials/01_basic.ipynb
@@ -887,11 +887,128 @@
"cell_type": "code",
"execution_count": 7,
"metadata": {},
- "outputs": [],
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "<div>\n",
+ "<style scoped>\n",
+ " .dataframe tbody tr th:only-of-type {\n",
+ " vertical-align: middle;\n",
+ " }\n",
+ "\n",
+ " .dataframe tbody tr th {\n",
+ " vertical-align: top;\n",
+ " }\n",
+ "\n",
+ " .dataframe thead th {\n",
+ " text-align: right;\n",
+ " }\n",
+ "</style>\n",
+ "<table border=\"1\" class=\"dataframe\">\n",
+ " <thead>\n",
+ " <tr style=\"text-align: right;\">\n",
+ " <th></th>\n",
+ " <th>dw_ek_borger</th>\n",
+ " <th>female</th>\n",
+ " </tr>\n",
+ " </thead>\n",
+ " <tbody>\n",
+ " <tr>\n",
+ " <th>0</th>\n",
+ " <td>0</td>\n",
+ " <td>0</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>1</th>\n",
+ " <td>1</td>\n",
+ " <td>1</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2</th>\n",
+ " <td>2</td>\n",
+ " <td>1</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>3</th>\n",
+ " <td>3</td>\n",
+ " <td>1</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>4</th>\n",
+ " <td>4</td>\n",
+ " <td>0</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>...</th>\n",
+ " <td>...</td>\n",
+ " <td>...</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>9994</th>\n",
+ " <td>9995</td>\n",
+ " <td>0</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>9995</th>\n",
+ " <td>9996</td>\n",
+ " <td>0</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>9996</th>\n",
+ " <td>9997</td>\n",
+ " <td>1</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>9997</th>\n",
+ " <td>9998</td>\n",
+ " <td>1</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>9998</th>\n",
+ " <td>9999</td>\n",
+ " <td>0</td>\n",
+ " </tr>\n",
+ " </tbody>\n",
+ "</table>\n",
+ "<p>9999 rows × 2 columns</p>\n",
+ "</div>"
+ ],
+ "text/plain": [
+ " dw_ek_borger female\n",
+ "0 0 0\n",
+ "1 1 1\n",
+ "2 2 1\n",
+ "3 3 1\n",
+ "4 4 0\n",
+ "... ... ...\n",
+ "9994 9995 0\n",
+ "9995 9996 0\n",
+ "9996 9997 1\n",
+ "9997 9998 1\n",
+ "9998 9999 0\n",
+ "\n",
+ "[9999 rows x 2 columns]"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
"source": [
"sex_predictor_spec = StaticSpec(\n",
- " values_df=df_synth_sex, feature_name=\"female\", prefix=\"pred\"\n",
- ")"
+ " values_df=df_synth_sex, feature_name=\"female\", prefix=\"pred\", input_col_name_override=\"female\"\n",
+ ")\n",
+ "\n",
+ "df_synth_sex"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that we also specify the \"input_col_name_override\", because the df_synth_sex df has its values in the \"female\" column. By default, tsflattener looks for a column names \"value\"."
]
},
{
@@ -910,9 +1027,21 @@
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": 9,
"metadata": {},
"outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "2022-12-07 13:52:04 [INFO] There were unprocessed specs, computing...\n",
+ "100%|██████████| 2/2 [00:00<00:00, 2.37it/s]\n",
+ "2022-12-07 13:52:05 [INFO] Processing complete, concatenating\n",
+ "2022-12-07 13:52:05 [INFO] Starting concatenation. Will take some time on performant systems, e.g. 30s for 100 features. This is normal.\n",
+ "2022-12-07 13:52:05 [INFO] Concatenation took 0.002 seconds\n",
+ "2022-12-07 13:52:05 [INFO] Merging with original df\n"
+ ]
+ },
{
"data": {
"text/html": [
@@ -921,31 +1050,31 @@
"│ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ │\n",
"│ ┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> dataframe </span>┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Values </span>┃ ┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Column Type </span>┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Count </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ │\n",
- "│ │ Number of rows │ 10000 │ │ int64 │ 2 │ │\n",
+ "│ │ Number of rows │ 4001 │ │ int64 │ 2 │ │\n",
"│ │ Number of columns │ 6 │ │ float64 │ 2 │ │\n",
"│ └───────────────────┴────────┘ │ datetime64 │ 1 │ │\n",
"│ │ string │ 1 │ │\n",
"│ └─────────────┴───────┘ │\n",
"│ <span style=\"font-style: italic\"> number </span> │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┓ │\n",
- "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">dw_ek_borger </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7400</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█████▇</span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_female </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.49</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█ █</span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_predictor_name_ </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1100</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 11</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.015</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.9</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.2</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.9</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▃██▃▁</span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">outc_outcome_name_wi </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.056</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.23</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> █ </span> │ │\n",
- "│ └───────────────────────────┴────────┴────────┴─────────┴────────┴─────────┴───────┴───────┴────────┴────────┘ │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
+ "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">dw_ek_borger </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2600</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█████▇ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">outc_outcome_name_wi </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.064</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.25</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█ ▁ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_predictor_name_ </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 72</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.097</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.9</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.9</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▃██▃▁ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_female </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.49</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█ █ </span> │ │\n",
+ "│ └────────────────────────────┴─────┴────────┴─────────┴────────┴─────────┴────────┴───────┴────────┴─────────┘ │\n",
"│ <span style=\"font-style: italic\"> datetime </span> │\n",
"│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
"│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> first </span>┃<span style=\"font-weight: bold\"> last </span>┃<span style=\"font-weight: bold\"> frequency </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">timestamp </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1965-01-02 09:35:00 </span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1969-12-31 21:42:00 </span> │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">None </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">timestamp </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1967-01-02 01:16:00 </span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1968-12-31 04:39:00 </span> │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">None </span> │ │\n",
"│ └──────────────────┴──────┴─────────┴────────────────────────────┴────────────────────────────┴──────────────┘ │\n",
"│ <span style=\"font-style: italic\"> string </span> │\n",
"│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓ │\n",
"│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> words per row </span>┃<span style=\"font-weight: bold\"> total words </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">prediction_time_uuid </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">prediction_time_uuid </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 4000</span> │ │\n",
"│ └───────────────────────────────────────┴───────┴───────────┴──────────────────────────┴─────────────────────┘ │\n",
"╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯\n",
"</pre>\n"
@@ -956,31 +1085,31 @@
"│ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ │\n",
"│ ┃\u001b[1;36m \u001b[0m\u001b[1;36mdataframe \u001b[0m\u001b[1;36m \u001b[0m┃\u001b[1;36m \u001b[0m\u001b[1;36mValues\u001b[0m\u001b[1;36m \u001b[0m┃ ┃\u001b[1;36m \u001b[0m\u001b[1;36mColumn Type\u001b[0m\u001b[1;36m \u001b[0m┃\u001b[1;36m \u001b[0m\u001b[1;36mCount\u001b[0m\u001b[1;36m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ │\n",
- "│ │ Number of rows │ 10000 │ │ int64 │ 2 │ │\n",
+ "│ │ Number of rows │ 4001 │ │ int64 │ 2 │ │\n",
"│ │ Number of columns │ 6 │ │ float64 │ 2 │ │\n",
"│ └───────────────────┴────────┘ │ datetime64 │ 1 │ │\n",
"│ │ string │ 1 │ │\n",
"│ └─────────────┴───────┘ │\n",
"│ \u001b[3m number \u001b[0m │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┓ │\n",
- "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mdw_ek_borger \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7400\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m█████▇\u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_female \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.49\u001b[0m │ \u001b[36m 0.5\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m█ █\u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_predictor_name_ \u001b[0m │ \u001b[36m 1100\u001b[0m │ \u001b[36m 11\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 0.015\u001b[0m │ \u001b[36m 3.9\u001b[0m │ \u001b[36m 6.2\u001b[0m │ \u001b[36m 9.9\u001b[0m │ \u001b[32m▁▃██▃▁\u001b[0m │ │\n",
- "│ │ \u001b[38;5;141moutc_outcome_name_wi \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.056\u001b[0m │ \u001b[36m 0.23\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m █ \u001b[0m │ │\n",
- "│ └───────────────────────────┴────────┴────────┴─────────┴────────┴─────────┴───────┴───────┴────────┴────────┘ │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
+ "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
+ "│ │ \u001b[38;5;141mdw_ek_borger \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 3\u001b[0m │ \u001b[36m 2600\u001b[0m │ \u001b[36m 7500\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m█████▇ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141moutc_outcome_name_wi \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.064\u001b[0m │ \u001b[36m 0.25\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m█ ▁ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_predictor_name_ \u001b[0m │ \u001b[36m 72\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 1.6\u001b[0m │ \u001b[36m 0.097\u001b[0m │ \u001b[36m 3.9\u001b[0m │ \u001b[36m 6\u001b[0m │ \u001b[36m 9.9\u001b[0m │ \u001b[32m▁▃██▃▁ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_female \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.49\u001b[0m │ \u001b[36m 0.5\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m█ █ \u001b[0m │ │\n",
+ "│ └────────────────────────────┴─────┴────────┴─────────┴────────┴─────────┴────────┴───────┴────────┴─────────┘ │\n",
"│ \u001b[3m datetime \u001b[0m │\n",
"│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
"│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mfirst \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mlast \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mfrequency \u001b[0m\u001b[1m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mtimestamp \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[31m 1965-01-02 09:35:00 \u001b[0m │ \u001b[31m 1969-12-31 21:42:00 \u001b[0m │ \u001b[38;5;141mNone \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mtimestamp \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[31m 1967-01-02 01:16:00 \u001b[0m │ \u001b[31m 1968-12-31 04:39:00 \u001b[0m │ \u001b[38;5;141mNone \u001b[0m │ │\n",
"│ └──────────────────┴──────┴─────────┴────────────────────────────┴────────────────────────────┴──────────────┘ │\n",
"│ \u001b[3m string \u001b[0m │\n",
"│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓ │\n",
"│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mwords per row \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mtotal words \u001b[0m\u001b[1m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mprediction_time_uuid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 10000\u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mprediction_time_uuid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 4000\u001b[0m │ │\n",
"│ └───────────────────────────────────────┴───────┴───────────┴──────────────────────────┴─────────────────────┘ │\n",
"╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯\n"
]
@@ -1012,9 +1141,9 @@
" <th>dw_ek_borger</th>\n",
" <th>timestamp</th>\n",
" <th>prediction_time_uuid</th>\n",
- " <th>pred_female</th>\n",
- " <th>pred_predictor_name_within_730_days_None_fallback_nan</th>\n",
" <th>outc_outcome_name_within_365_days_None_fallback_0_dichotomous</th>\n",
+ " <th>pred_predictor_name_within_730_days_None_fallback_nan</th>\n",
+ " <th>pred_female</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
@@ -1023,45 +1152,45 @@
" <td>9903</td>\n",
" <td>1968-05-09 21:24:00</td>\n",
" <td>9903-1968-05-09-21-24-00</td>\n",
- " <td>0</td>\n",
- " <td>0.990763</td>\n",
" <td>0.0</td>\n",
+ " <td>0.990763</td>\n",
+ " <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
- " <td>7465</td>\n",
- " <td>1966-05-24 01:23:00</td>\n",
- " <td>7465-1966-05-24-01-23-00</td>\n",
- " <td>1</td>\n",
- " <td>0.819872</td>\n",
- " <td>0.0</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>2</th>\n",
" <td>6447</td>\n",
" <td>1967-09-25 18:08:00</td>\n",
" <td>6447-1967-09-25-18-08-00</td>\n",
- " <td>1</td>\n",
+ " <td>0.0</td>\n",
" <td>5.582745</td>\n",
+ " <td>1</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2</th>\n",
+ " <td>4927</td>\n",
+ " <td>1968-06-30 12:13:00</td>\n",
+ " <td>4927-1968-06-30-12-13-00</td>\n",
" <td>0.0</td>\n",
+ " <td>4.957251</td>\n",
+ " <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
- " <td>2121</td>\n",
- " <td>1966-05-05 20:52:00</td>\n",
- " <td>2121-1966-05-05-20-52-00</td>\n",
- " <td>0</td>\n",
- " <td>7.627190</td>\n",
+ " <td>5475</td>\n",
+ " <td>1967-01-09 03:09:00</td>\n",
+ " <td>5475-1967-01-09-03-09-00</td>\n",
" <td>0.0</td>\n",
+ " <td>5.999336</td>\n",
+ " <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
- " <td>4927</td>\n",
- " <td>1968-06-30 12:13:00</td>\n",
- " <td>4927-1968-06-30-12-13-00</td>\n",
- " <td>0</td>\n",
- " <td>4.957251</td>\n",
+ " <td>9793</td>\n",
+ " <td>1968-12-15 12:59:00</td>\n",
+ " <td>9793-1968-12-15-12-59-00</td>\n",
" <td>0.0</td>\n",
+ " <td>7.294038</td>\n",
+ " <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>...</th>\n",
@@ -1073,99 +1202,99 @@
" <td>...</td>\n",
" </tr>\n",
" <tr>\n",
- " <th>9995</th>\n",
- " <td>7159</td>\n",
- " <td>1966-12-12 16:32:00</td>\n",
- " <td>7159-1966-12-12-16-32-00</td>\n",
- " <td>0</td>\n",
- " <td>7.060570</td>\n",
+ " <th>3996</th>\n",
+ " <td>6542</td>\n",
+ " <td>1967-04-15 14:37:00</td>\n",
+ " <td>6542-1967-04-15-14-37-00</td>\n",
" <td>0.0</td>\n",
+ " <td>7.137424</td>\n",
+ " <td>1</td>\n",
" </tr>\n",
" <tr>\n",
- " <th>9996</th>\n",
- " <td>147</td>\n",
- " <td>1965-03-12 05:32:00</td>\n",
- " <td>147-1965-03-12-05-32-00</td>\n",
- " <td>1</td>\n",
- " <td>NaN</td>\n",
+ " <th>3997</th>\n",
+ " <td>4228</td>\n",
+ " <td>1967-02-26 05:45:00</td>\n",
+ " <td>4228-1967-02-26-05-45-00</td>\n",
" <td>0.0</td>\n",
+ " <td>3.792014</td>\n",
+ " <td>0</td>\n",
" </tr>\n",
" <tr>\n",
- " <th>9997</th>\n",
+ " <th>3998</th>\n",
+ " <td>3385</td>\n",
+ " <td>1967-07-17 19:18:00</td>\n",
+ " <td>3385-1967-07-17-19-18-00</td>\n",
+ " <td>0.0</td>\n",
+ " <td>5.769484</td>\n",
+ " <td>1</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>3999</th>\n",
" <td>1421</td>\n",
" <td>1968-04-15 15:53:00</td>\n",
" <td>1421-1968-04-15-15-53-00</td>\n",
- " <td>0</td>\n",
- " <td>7.732447</td>\n",
" <td>0.0</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>9998</th>\n",
- " <td>3353</td>\n",
- " <td>1966-01-15 10:04:00</td>\n",
- " <td>3353-1966-01-15-10-04-00</td>\n",
+ " <td>7.732447</td>\n",
" <td>0</td>\n",
- " <td>7.658063</td>\n",
- " <td>0.0</td>\n",
" </tr>\n",
" <tr>\n",
- " <th>9999</th>\n",
+ " <th>4000</th>\n",
" <td>1940</td>\n",
" <td>1968-05-17 10:49:00</td>\n",
" <td>1940-1968-05-17-10-49-00</td>\n",
- " <td>0</td>\n",
- " <td>4.846514</td>\n",
" <td>0.0</td>\n",
+ " <td>4.846514</td>\n",
+ " <td>0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
- "<p>10000 rows × 6 columns</p>\n",
+ "<p>4001 rows × 6 columns</p>\n",
"</div>"
],
"text/plain": [
- " dw_ek_borger timestamp prediction_time_uuid pred_female \\\n",
- "0 9903 1968-05-09 21:24:00 9903-1968-05-09-21-24-00 0 \n",
- "1 7465 1966-05-24 01:23:00 7465-1966-05-24-01-23-00 1 \n",
- "2 6447 1967-09-25 18:08:00 6447-1967-09-25-18-08-00 1 \n",
- "3 2121 1966-05-05 20:52:00 2121-1966-05-05-20-52-00 0 \n",
- "4 4927 1968-06-30 12:13:00 4927-1968-06-30-12-13-00 0 \n",
- "... ... ... ... ... \n",
- "9995 7159 1966-12-12 16:32:00 7159-1966-12-12-16-32-00 0 \n",
- "9996 147 1965-03-12 05:32:00 147-1965-03-12-05-32-00 1 \n",
- "9997 1421 1968-04-15 15:53:00 1421-1968-04-15-15-53-00 0 \n",
- "9998 3353 1966-01-15 10:04:00 3353-1966-01-15-10-04-00 0 \n",
- "9999 1940 1968-05-17 10:49:00 1940-1968-05-17-10-49-00 0 \n",
+ " dw_ek_borger timestamp prediction_time_uuid \\\n",
+ "0 9903 1968-05-09 21:24:00 9903-1968-05-09-21-24-00 \n",
+ "1 6447 1967-09-25 18:08:00 6447-1967-09-25-18-08-00 \n",
+ "2 4927 1968-06-30 12:13:00 4927-1968-06-30-12-13-00 \n",
+ "3 5475 1967-01-09 03:09:00 5475-1967-01-09-03-09-00 \n",
+ "4 9793 1968-12-15 12:59:00 9793-1968-12-15-12-59-00 \n",
+ "... ... ... ... \n",
+ "3996 6542 1967-04-15 14:37:00 6542-1967-04-15-14-37-00 \n",
+ "3997 4228 1967-02-26 05:45:00 4228-1967-02-26-05-45-00 \n",
+ "3998 3385 1967-07-17 19:18:00 3385-1967-07-17-19-18-00 \n",
+ "3999 1421 1968-04-15 15:53:00 1421-1968-04-15-15-53-00 \n",
+ "4000 1940 1968-05-17 10:49:00 1940-1968-05-17-10-49-00 \n",
"\n",
- " pred_predictor_name_within_730_days_None_fallback_nan \\\n",
- "0 0.990763 \n",
- "1 0.819872 \n",
- "2 5.582745 \n",
- "3 7.627190 \n",
- "4 4.957251 \n",
- "... ... \n",
- "9995 7.060570 \n",
- "9996 NaN \n",
- "9997 7.732447 \n",
- "9998 7.658063 \n",
- "9999 4.846514 \n",
+ " outc_outcome_name_within_365_days_None_fallback_0_dichotomous \\\n",
+ "0 0.0 \n",
+ "1 0.0 \n",
+ "2 0.0 \n",
+ "3 0.0 \n",
+ "4 0.0 \n",
+ "... ... \n",
+ "3996 0.0 \n",
+ "3997 0.0 \n",
+ "3998 0.0 \n",
+ "3999 0.0 \n",
+ "4000 0.0 \n",
"\n",
- " outc_outcome_name_within_365_days_None_fallback_0_dichotomous \n",
- "0 0.0 \n",
- "1 0.0 \n",
- "2 0.0 \n",
- "3 0.0 \n",
- "4 0.0 \n",
- "... ... \n",
- "9995 0.0 \n",
- "9996 0.0 \n",
- "9997 0.0 \n",
- "9998 0.0 \n",
- "9999 0.0 \n",
+ " pred_predictor_name_within_730_days_None_fallback_nan pred_female \n",
+ "0 0.990763 0 \n",
+ "1 5.582745 1 \n",
+ "2 4.957251 0 \n",
+ "3 5.999336 0 \n",
+ "4 7.294038 0 \n",
+ "... ... ... \n",
+ "3996 7.137424 1 \n",
+ "3997 3.792014 0 \n",
+ "3998 5.769484 1 \n",
+ "3999 7.732447 0 \n",
+ "4000 4.846514 0 \n",
"\n",
- "[10000 rows x 6 columns]"
+ "[4001 rows x 6 columns]"
]
},
- "execution_count": 8,
+ "execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
@@ -1178,11 +1307,10 @@
" id_col_name=\"dw_ek_borger\",\n",
" timestamp_col_name=\"timestamp\",\n",
" n_workers=1,\n",
+ " drop_pred_times_with_insufficient_look_distance=True,\n",
")\n",
"\n",
- "ts_flattener.add_static_info(static_spec=sex_predictor_spec)\n",
- "ts_flattener.add_temporal_predictor(output_spec=temporal_predictor_spec)\n",
- "ts_flattener.add_temporal_outcome(output_spec=outcome_spec)\n",
+ "ts_flattener.add_spec([sex_predictor_spec, temporal_predictor_spec, outcome_spec])\n",
"\n",
"df = ts_flattener.get_df()\n",
"\n",
@@ -1199,9 +1327,7 @@
"2. Timestamps for each prediction time\n",
"3. A unique identifier for each prediciton-time\n",
"4. Our predictor columns, prefixed with `pred_` and\n",
- "5. Our outcome columns, prefixed with `outc_`\n",
- "\n",
- "Note that the high proportion of NAs is due to the way we generate synthetic data. Specifically, we randomly generate entity IDs, so some IDs won't be represented in our predictors."
+ "5. Our outcome columns, prefixed with `outc_`"
]
}
],
|
Aarhus-Psychiatry-Research__timeseriesflattener-54
|
[
{
"changes": {
"added_entities": [
"src/timeseriesflattener/feature_spec_objects.py:resolve_from_dict_or_registry",
"src/timeseriesflattener/feature_spec_objects.py:MinGroupSpec._check_loaders_are_valid"
],
"added_modules": [
"src/timeseriesflattener/feature_spec_objects.py:resolve_from_dict_or_registry"
],
"edited_entities": [
"src/timeseriesflattener/feature_spec_objects.py:resolve_values_df",
"src/timeseriesflattener/feature_spec_objects.py:MinGroupSpec.__init__"
],
"edited_modules": [
"src/timeseriesflattener/feature_spec_objects.py:resolve_values_df",
"src/timeseriesflattener/feature_spec_objects.py:AnySpec",
"src/timeseriesflattener/feature_spec_objects.py:MinGroupSpec"
]
},
"file": "src/timeseriesflattener/feature_spec_objects.py"
},
{
"changes": {
"added_entities": [
"src/timeseriesflattener/utils.py:split_df_and_register_to_dict"
],
"added_modules": [
"src/timeseriesflattener/utils.py:split_df_and_register_to_dict"
],
"edited_entities": null,
"edited_modules": null
},
"file": "src/timeseriesflattener/utils.py"
}
] |
Aarhus-Psychiatry-Research/timeseriesflattener
|
ef219b6b829c1f29dabbe13b503fca12adaaeaad
|
feat: take multiple features as long format
|
diff --git a/src/timeseriesflattener/feature_spec_objects.py b/src/timeseriesflattener/feature_spec_objects.py
index 0ae0db2..e739fa9 100644
--- a/src/timeseriesflattener/feature_spec_objects.py
+++ b/src/timeseriesflattener/feature_spec_objects.py
@@ -12,7 +12,7 @@ from pydantic import BaseModel as PydanticBaseModel
from pydantic import Extra
from timeseriesflattener.resolve_multiple_functions import resolve_multiple_fns
-from timeseriesflattener.utils import data_loaders
+from timeseriesflattener.utils import data_loaders, split_df_dict
log = logging.getLogger(__name__)
@@ -40,18 +40,12 @@ def in_dict_and_not_none(d: dict, key: str) -> bool:
return key in d and d[key] is not None
-def resolve_values_df(data: dict[str, Any]):
- """Resolve the values_df attribute to a dataframe."""
- if "values_loader" not in data and "values_df" not in data:
- raise ValueError("Either values_loader or a dataframe must be specified.")
-
- if in_dict_and_not_none(d=data, key="values_loader") and in_dict_and_not_none(
- key="values_df",
- d=data,
- ):
- raise ValueError("Only one of values_loader or df can be specified.")
-
- if "values_df" not in data or data["values_df"] is None:
+def resolve_from_dict_or_registry(data: dict[str, Any]):
+ """Resolve values_df from a dictionary or registry."""
+ if "values_name" in data and data["values_name"] is not None:
+ data["values_df"] = split_df_dict.get(data["values_name"])
+ data["feature_name"] = data["values_name"]
+ else:
if isinstance(data["values_loader"], str):
data["feature_name"] = data["values_loader"]
data["values_loader"] = data_loaders.get(data["values_loader"])
@@ -66,6 +60,28 @@ def resolve_values_df(data: dict[str, Any]):
feature_name=data["feature_name"],
)
+
+def resolve_values_df(data: dict[str, Any]):
+ """Resolve the values_df attribute to a dataframe."""
+ if not any(key in data for key in ["values_loader", "values_name", "values_df"]):
+ raise ValueError(
+ "Either values_loader or a dictionary containing dataframes or a single dataframe must be specified.",
+ )
+
+ if (
+ sum(
+ in_dict_and_not_none(data, key)
+ for key in ["values_loader", "values_name", "values_df"]
+ )
+ > 1
+ ):
+ raise ValueError(
+ "Only one of values_loader or values_name or df can be specified.",
+ )
+
+ if "values_df" not in data or data["values_df"] is None:
+ resolve_from_dict_or_registry(data)
+
if not isinstance(data["values_df"], pd.DataFrame):
raise ValueError("values_df must be or resolve to a pandas DataFrame.")
@@ -115,6 +131,10 @@ class AnySpec(BaseModel):
# Loader for the df. Tries to resolve from the resolve_multiple_nfs registry,
# then calls the function which should return a dataframe.
+ values_name: Optional[str] = None
+ # A string that corresponds to a key in a dictionary of multiple dataframes that
+ # correspods to a name of a type of values.
+
loader_kwargs: Optional[dict[str, Any]] = None
# Optional kwargs for the values_loader
@@ -187,7 +207,7 @@ class StaticSpec(AnySpec):
class TemporalSpec(AnySpec):
- """The minimum specification required for all collapsed time series
+ """The minimum specification required for all collapsed time series.
(temporal features), whether looking ahead or behind.
@@ -301,7 +321,7 @@ class PredictorSpec(TemporalSpec):
class OutcomeSpec(TemporalSpec):
- """Specification for a single predictor, where the df has been resolved."""
+ """Specification for a single outcome, where the df has been resolved."""
prefix: str = "outc"
@@ -357,17 +377,19 @@ class OutcomeSpec(TemporalSpec):
class MinGroupSpec(BaseModel):
- """Minimum specification for a group of features, whether they're looking
-
- ahead or behind.
+ """Minimum specification for a group of features, whether they're looking ahead or behind.
Used to generate combinations of features.
"""
- values_loader: list[str]
- # Loader for the df. Tries to resolve from the resolve_multiple_nfs registry,
+ values_loader: Optional[list[str]] = None
+ # Loader for the df. Tries to resolve from the data_loaders registry,
# then calls the function which should return a dataframe.
+ values_name: Optional[list[str]] = None
+ # List of strings that corresponds to a key in a dictionary of multiple dataframes
+ # that correspods to a name of a type of values.
+
values_df: Optional[pd.DataFrame] = None
# Dataframe with the values.
@@ -387,12 +409,9 @@ class MinGroupSpec(BaseModel):
# If NaN is higher than this in the input dataframe during resolution, raise an error.
prefix: Optional[str] = None
- # Prefix for the column name. Overrides the default prefix for the feature type.
-
- def __init__(self, **data):
- super().__init__(**data)
- # Check that all passed loaders are valid
+ def _check_loaders_are_valid(self):
+ """Check that all loaders can be resolved from the data_loaders catalogue."""
invalid_loaders = list(
set(self.values_loader) - set(data_loaders.get_all().keys()),
)
@@ -415,6 +434,15 @@ class MinGroupSpec(BaseModel):
f"""Available loaders:{nl}{avail_loaders_str}""",
)
+ # Prefix for the column name. Overrides the default prefix for the feature type.
+
+ def __init__(self, **data):
+ super().__init__(**data)
+
+ # Check that all passed loaders are valid
+ if self.values_loader is not None:
+ self._check_loaders_are_valid()
+
if self.output_col_name_override:
input_col_name = (
"value"
diff --git a/src/timeseriesflattener/utils.py b/src/timeseriesflattener/utils.py
index a602b18..2ef4adb 100644
--- a/src/timeseriesflattener/utils.py
+++ b/src/timeseriesflattener/utils.py
@@ -14,10 +14,56 @@ import catalogue
import pandas as pd
data_loaders = catalogue.create("timeseriesflattener", "data_loaders")
+split_df_dict = {}
+
PROJECT_ROOT = Path(__file__).resolve().parents[2]
+def split_df_and_register_to_dict(
+ df: pd.DataFrame,
+ id_col_name: str = "dw_ek_borger",
+ timestamp_col_name: str = "timestamp",
+ value_col_name: str = "value",
+ value_names_col_name: str = "value_names",
+):
+ """Split a df with multiple different value types into dataframes only containing values for each specific value type.
+
+ Registers the seperated dfs in the df_dict.
+
+ Args:
+ df (pd.DataFrame): A dataframe in long format containing the values to be grouped into a catalogue.
+ id_col_name (str): Name of the column containing the patient id for each value. Defaults to "dw_ek_borger".
+ timestamp_col_name (str): Name of the column containing the timestamp for each value. Defaults to "timestamp".
+ value_col_name (str): Name of the column containing the value for each value. Defaults to "values".
+ value_names_col_name (str): Name of the column containing the names of the different types of values for each value. Defaults to "value_names".
+ """
+ passed_columns = [
+ id_col_name,
+ timestamp_col_name,
+ value_col_name,
+ value_names_col_name,
+ ]
+ missing_columns = [col for col in passed_columns if col not in list(df.columns)]
+
+ # If any of the required columns is missing, raise an error
+ if len(missing_columns) > 0:
+ raise ValueError(
+ f"The following required column(s) is/are missing from the input dataframe: {missing_columns}. Available columns are {df.columns}.",
+ )
+
+ # Get the unique value names from the dataframe
+ value_names = df[value_names_col_name].unique()
+
+ for value_name in value_names:
+
+ value_df = df[df[value_names_col_name] == value_name][
+ [id_col_name, timestamp_col_name, value_col_name]
+ ]
+
+ split_df_dict[value_name] = value_df
+
+
def format_dict_for_printing(d: dict) -> str:
"""Format a dictionary for printing. Removes extra apostrophes, formats
|
Aarhus-Psychiatry-Research__timeseriesflattener-59
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"src/timeseriesflattener/feature_spec_objects.py:TemporalSpec"
]
},
"file": "src/timeseriesflattener/feature_spec_objects.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.__init__",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._flatten_temporal_values_to_df"
],
"edited_modules": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener"
]
},
"file": "src/timeseriesflattener/flattened_dataset.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/timeseriesflattener/utils.py:split_df_and_register_to_dict"
],
"edited_modules": [
"src/timeseriesflattener/utils.py:split_df_and_register_to_dict"
]
},
"file": "src/timeseriesflattener/utils.py"
}
] |
Aarhus-Psychiatry-Research/timeseriesflattener
|
505b6c86f16299ce5643c4eb2e12f0a444a4394b
|
refactor: remove mentions of dw_ek_borger (waiting for no open PRs, very likely to cause conflicts)
1. Rename all occurences of "dw_ek_borger" to "entity_id"
2. Remove it as a default in Timeseriesflattener
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d9d748..5ba85d0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,13 +2,6 @@
<!--next-version-placeholder-->
-## v0.19.0 (2022-12-08)
-### Feature
-* More informative errors ([`3141487`](https://github.com/Aarhus-Psychiatry-Research/timeseriesflattener/commit/3141487a04cb815ac492e632a601265c5c72d65f))
-
-### Documentation
-* More docstrings ([`e1134d4`](https://github.com/Aarhus-Psychiatry-Research/timeseriesflattener/commit/e1134d40949af8ca5f547f9f015ea57e5ea6ee4c))
-
## v0.18.0 (2022-12-08)
### Feature
* Take multiple features as long format ([`7f771e4`](https://github.com/Aarhus-Psychiatry-Research/timeseriesflattener/commit/7f771e4ece71bff5bbf24a2718121709ead1792b))
diff --git a/pyproject.toml b/pyproject.toml
index 4fb4b4e..87da589 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "timeseriesflattener"
-version = "0.19.0"
+version = "0.18.0"
description = "A package for converting time series data from e.g. electronic health records into wide format data."
readme = "README.md"
authors = ["Martin Bernstorff", "Kenneth Enevoldsen", "Jakob Grøhn Damgaard", "Frida Hæstrup", "Lasse Hansen"]
diff --git a/src/timeseriesflattener/feature_spec_objects.py b/src/timeseriesflattener/feature_spec_objects.py
index e739fa9..b498393 100644
--- a/src/timeseriesflattener/feature_spec_objects.py
+++ b/src/timeseriesflattener/feature_spec_objects.py
@@ -229,7 +229,7 @@ class TemporalSpec(AnySpec):
allowed_nan_value_prop: float = 0.0
# If NaN is higher than this in the input dataframe during resolution, raise an error.
- id_col_name: str = "dw_ek_borger"
+ id_col_name: str = "id"
# Col name for ids in the input dataframe.
timestamp_col_name: str = "timestamp"
diff --git a/src/timeseriesflattener/flattened_dataset.py b/src/timeseriesflattener/flattened_dataset.py
index 83c5d85..fa5dba2 100644
--- a/src/timeseriesflattener/flattened_dataset.py
+++ b/src/timeseriesflattener/flattened_dataset.py
@@ -89,7 +89,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
prediction_times_df: DataFrame,
drop_pred_times_with_insufficient_look_distance: bool, # noqa
cache: Optional[FeatureCache] = None,
- id_col_name: str = "dw_ek_borger",
+ id_col_name: str = "id",
timestamp_col_name: str = "timestamp",
predictor_col_name_prefix: str = "pred",
outcome_col_name_prefix: str = "outc",
@@ -122,7 +122,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
Args:
prediction_times_df (DataFrame): Dataframe with prediction times, required cols: patient_id, .
cache (Optional[FeatureCache], optional): Object for feature caching. Should be initialised when passed to init. Defaults to None.
- id_col_name (str, optional): Column namn name for patients ids. Is used across outcome and predictors. Defaults to "dw_ek_borger".
+ id_col_name (str, optional): Column namn name for patients ids. Is used across outcome and predictors. Defaults to "id".
timestamp_col_name (str, optional): Column name name for timestamps. Is used across outcomes and predictors. Defaults to "timestamp".
predictor_col_name_prefix (str, optional): Prefix for predictor col names. Defaults to "pred_".
outcome_col_name_prefix (str, optional): Prefix for outcome col names. Defaults to "outc_".
@@ -324,7 +324,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
DataFrame
"""
# Generate df with one row for each prediction time x event time combination
- # Drop dw_ek_borger for faster merge
+ # Drop id for faster merge
df = pd.merge(
left=prediction_times_with_uuid_df,
right=output_spec.values_df,
@@ -332,7 +332,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
on=id_col_name,
suffixes=("_pred", "_val"),
validate="m:m",
- ).drop("dw_ek_borger", axis=1)
+ ).drop(id_col_name, axis=1)
# Drop prediction times without event times within interval days
if isinstance(output_spec, OutcomeSpec):
diff --git a/src/timeseriesflattener/utils.py b/src/timeseriesflattener/utils.py
index 2ef4adb..7913759 100644
--- a/src/timeseriesflattener/utils.py
+++ b/src/timeseriesflattener/utils.py
@@ -22,7 +22,7 @@ PROJECT_ROOT = Path(__file__).resolve().parents[2]
def split_df_and_register_to_dict(
df: pd.DataFrame,
- id_col_name: str = "dw_ek_borger",
+ id_col_name: str = "id",
timestamp_col_name: str = "timestamp",
value_col_name: str = "value",
value_names_col_name: str = "value_names",
@@ -33,7 +33,7 @@ def split_df_and_register_to_dict(
Args:
df (pd.DataFrame): A dataframe in long format containing the values to be grouped into a catalogue.
- id_col_name (str): Name of the column containing the patient id for each value. Defaults to "dw_ek_borger".
+ id_col_name (str): Name of the column containing the patient id for each value. Defaults to "id".
timestamp_col_name (str): Name of the column containing the timestamp for each value. Defaults to "timestamp".
value_col_name (str): Name of the column containing the value for each value. Defaults to "values".
value_names_col_name (str): Name of the column containing the names of the different types of values for each value. Defaults to "value_names".
diff --git a/tutorials/01_basic.ipynb b/tutorials/01_basic.ipynb
index 4616fb1..ceecc96 100644
--- a/tutorials/01_basic.ipynb
+++ b/tutorials/01_basic.ipynb
@@ -56,7 +56,7 @@
"│ ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┓ │\n",
"│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">dw_ek_borger </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7400</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> █████▇ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">id </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7400</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> █████▇ </span> │ │\n",
"│ └─────────────────────┴──────┴─────────┴─────────┴─────────┴──────┴─────────┴─────────┴──────────┴───────────┘ │\n",
"│ <span style=\"font-style: italic\"> datetime </span> │\n",
"│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
@@ -80,7 +80,7 @@
"│ ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┓ │\n",
"│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mdw_ek_borger \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7400\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m █████▇ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7400\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m █████▇ \u001b[0m │ │\n",
"│ └─────────────────────┴──────┴─────────┴─────────┴─────────┴──────┴─────────┴─────────┴──────────┴───────────┘ │\n",
"│ \u001b[3m datetime \u001b[0m │\n",
"│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
@@ -115,7 +115,7 @@
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
- " <th>dw_ek_borger</th>\n",
+ " <th>id</th>\n",
" <th>timestamp</th>\n",
" </tr>\n",
" </thead>\n",
@@ -181,7 +181,7 @@
"</div>"
],
"text/plain": [
- " dw_ek_borger timestamp\n",
+ " id timestamp\n",
"0 9903 1968-05-09 21:24:00\n",
"1 7465 1966-05-24 01:23:00\n",
"2 6447 1967-09-25 18:08:00\n",
@@ -240,7 +240,7 @@
"│ ┏━━━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓ │\n",
"│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">dw_ek_borger </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ██████ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">id </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ██████ </span> │ │\n",
"│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">value </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.9</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.00015</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ██████ </span> │ │\n",
"│ └────────────────────┴──────┴─────────┴────────┴────────┴────────────┴────────┴────────┴──────────┴──────────┘ │\n",
"│ <span style=\"font-style: italic\"> datetime </span> │\n",
@@ -266,7 +266,7 @@
"│ ┏━━━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┓ │\n",
"│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mdw_ek_borger \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7500\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m ██████ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7500\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m ██████ \u001b[0m │ │\n",
"│ │ \u001b[38;5;141mvalue \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 2.9\u001b[0m │ \u001b[36m 0.00015\u001b[0m │ \u001b[36m 2.5\u001b[0m │ \u001b[36m 7.5\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m ██████ \u001b[0m │ │\n",
"│ └────────────────────┴──────┴─────────┴────────┴────────┴────────────┴────────┴────────┴──────────┴──────────┘ │\n",
"│ \u001b[3m datetime \u001b[0m │\n",
@@ -302,7 +302,7 @@
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
- " <th>dw_ek_borger</th>\n",
+ " <th>id</th>\n",
" <th>timestamp</th>\n",
" <th>value</th>\n",
" </tr>\n",
@@ -380,7 +380,7 @@
"</div>"
],
"text/plain": [
- " dw_ek_borger timestamp value\n",
+ " id timestamp value\n",
"0 9476 1969-03-05 08:08:00 0.816995\n",
"1 4631 1967-04-10 22:48:00 4.818074\n",
"2 3890 1969-12-15 14:07:00 2.503789\n",
@@ -438,7 +438,7 @@
"│ ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┓ │\n",
"│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">dw_ek_borger </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ██████ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">id </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ██████ </span> │ │\n",
"│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">female </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> █ █ </span> │ │\n",
"│ └─────────────────────┴──────┴─────────┴─────────┴─────────┴──────┴─────────┴─────────┴──────────┴───────────┘ │\n",
"╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯\n",
@@ -457,7 +457,7 @@
"│ ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┓ │\n",
"│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mdw_ek_borger \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7500\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m ██████ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7500\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m ██████ \u001b[0m │ │\n",
"│ │ \u001b[38;5;141mfemale \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.5\u001b[0m │ \u001b[36m 0.5\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m █ █ \u001b[0m │ │\n",
"│ └─────────────────────┴──────┴─────────┴─────────┴─────────┴──────┴─────────┴─────────┴──────────┴───────────┘ │\n",
"╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯\n"
@@ -487,7 +487,7 @@
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
- " <th>dw_ek_borger</th>\n",
+ " <th>id</th>\n",
" <th>female</th>\n",
" </tr>\n",
" </thead>\n",
@@ -553,7 +553,7 @@
"</div>"
],
"text/plain": [
- " dw_ek_borger female\n",
+ " id female\n",
"0 0 0\n",
"1 1 1\n",
"2 2 1\n",
@@ -616,7 +616,7 @@
"│ ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┓ │\n",
"│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">dw_ek_borger </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 4</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7600</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ██▇███ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">id </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 4</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7600</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ██▇███ </span> │ │\n",
"│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">value </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> █ </span> │ │\n",
"│ └─────────────────────┴──────┴─────────┴─────────┴─────────┴──────┴─────────┴─────────┴──────────┴───────────┘ │\n",
"│ <span style=\"font-style: italic\"> datetime </span> │\n",
@@ -641,7 +641,7 @@
"│ ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┓ │\n",
"│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mdw_ek_borger \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 4\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7600\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m ██▇███ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 4\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7600\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m ██▇███ \u001b[0m │ │\n",
"│ │ \u001b[38;5;141mvalue \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m █ \u001b[0m │ │\n",
"│ └─────────────────────┴──────┴─────────┴─────────┴─────────┴──────┴─────────┴─────────┴──────────┴───────────┘ │\n",
"│ \u001b[3m datetime \u001b[0m │\n",
@@ -677,7 +677,7 @@
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
- " <th>dw_ek_borger</th>\n",
+ " <th>id</th>\n",
" <th>timestamp</th>\n",
" <th>value</th>\n",
" </tr>\n",
@@ -755,7 +755,7 @@
"</div>"
],
"text/plain": [
- " dw_ek_borger timestamp value\n",
+ " id timestamp value\n",
"1 4 1965-06-20 16:29:00 1\n",
"3 7 1968-10-16 01:46:00 1\n",
"6 12 1965-04-17 07:17:00 1\n",
@@ -860,7 +860,7 @@
"\n",
"How to handle multiple outcome values within interval days depends on your use case. In this case, we choose that any prediction time with at least one outcome (a timestamp labelled 1) within interval days is \"positive\". I.e., if there is both a 0 and a 1 within interval days, the prediction time should be labelled with a 1. We set resolve_multiple_fn = maximum to accomplish this.\n",
"\n",
- "We also specify that the outcome is not incident. This means that each entity id (dw_ek_borger) can experience the outcome more than once. \n",
+ "We also specify that the outcome is not incident. This means that each entity id (id) can experience the outcome more than once. \n",
"\n",
"If the outcome was marked as incident, all prediction times after the entity experiences the outcome are dropped.\n",
"\n",
@@ -942,7 +942,7 @@
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
- " <th>dw_ek_borger</th>\n",
+ " <th>id</th>\n",
" <th>female</th>\n",
" </tr>\n",
" </thead>\n",
@@ -1008,7 +1008,7 @@
"</div>"
],
"text/plain": [
- " dw_ek_borger female\n",
+ " id female\n",
"0 0 0\n",
"1 1 1\n",
"2 2 1\n",
@@ -1070,7 +1070,7 @@
"\n",
"ts_flattener = TimeseriesFlattener(\n",
" prediction_times_df=df_prediction_times,\n",
- " id_col_name=\"dw_ek_borger\",\n",
+ " id_col_name=\"id\",\n",
" timestamp_col_name=\"timestamp\",\n",
" n_workers=1,\n",
" drop_pred_times_with_insufficient_look_distance=True,\n",
@@ -1133,7 +1133,7 @@
"│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
"│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">dw_ek_borger </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2600</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█████▇ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">id </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2600</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█████▇ </span> │ │\n",
"│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_predictor_name_ </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 72</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.097</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.9</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.9</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▃██▃▁ </span> │ │\n",
"│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">outc_outcome_name_wi </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.064</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.25</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█ ▁ </span> │ │\n",
"│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_female </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.49</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█ █ </span> │ │\n",
@@ -1168,7 +1168,7 @@
"│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
"│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
"│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mdw_ek_borger \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 3\u001b[0m │ \u001b[36m 2600\u001b[0m │ \u001b[36m 7500\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m█████▇ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 3\u001b[0m │ \u001b[36m 2600\u001b[0m │ \u001b[36m 7500\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m█████▇ \u001b[0m │ │\n",
"│ │ \u001b[38;5;141mpred_predictor_name_ \u001b[0m │ \u001b[36m 72\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 1.6\u001b[0m │ \u001b[36m 0.097\u001b[0m │ \u001b[36m 3.9\u001b[0m │ \u001b[36m 6\u001b[0m │ \u001b[36m 9.9\u001b[0m │ \u001b[32m▁▃██▃▁ \u001b[0m │ │\n",
"│ │ \u001b[38;5;141moutc_outcome_name_wi \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.064\u001b[0m │ \u001b[36m 0.25\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m█ ▁ \u001b[0m │ │\n",
"│ │ \u001b[38;5;141mpred_female \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0.49\u001b[0m │ \u001b[36m 0.5\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[32m█ █ \u001b[0m │ │\n",
@@ -1212,7 +1212,7 @@
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
- " <th>dw_ek_borger</th>\n",
+ " <th>id</th>\n",
" <th>timestamp</th>\n",
" <th>prediction_time_uuid</th>\n",
" <th>pred_predictor_name_within_730_days_mean_fallback_nan</th>\n",
@@ -1326,7 +1326,7 @@
"</div>"
],
"text/plain": [
- " dw_ek_borger timestamp prediction_time_uuid \\\n",
+ " id timestamp prediction_time_uuid \\\n",
"0 9903 1968-05-09 21:24:00 9903-1968-05-09-21-24-00 \n",
"1 6447 1967-09-25 18:08:00 6447-1967-09-25-18-08-00 \n",
"2 4927 1968-06-30 12:13:00 4927-1968-06-30-12-13-00 \n",
diff --git a/tutorials/02_advanced.ipynb b/tutorials/02_advanced.ipynb
index 3f86125..b6f538f 100644
--- a/tutorials/02_advanced.ipynb
+++ b/tutorials/02_advanced.ipynb
@@ -1,751 +1,743 @@
{
- "cells": [
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "In the basic tutorial we covered how to add static features, predictors and outcomes.\n",
- "In this tutorial, we'll expand on that, covering how to effectively add many features by:\n",
- "1. Utilising data loaders in a data_loaders registry,\n",
- "2. Populating a dictionary from a long format dataframe,\n",
- "3. Creating feature combinations from specifcations,\n",
- "4. Using caching, so you can iterate on your datasets without having to complete full computations every time\n"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Using data loaders\n",
- "Until now, we've loaded our data first and then created combinations. But what if your data lies in an SQL database, and you don't want to save it to disk?\n",
- "\n",
- "Time to introduce feature loaders. All feature spec objects can resolve from a loader function. The only requirement of that loader function is that it should return a values dataframe, which should contain an ID column, a timestamp column and a list of vlaues. This means you can have loaders that load from REDIS, SQL databases, or just from disk. Whatever you prefer.\n",
- "\n",
- "This function is then called when you initialise a specification.\n",
- "\n",
- "This loader is specified in the values_loader key like so:\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "from skimpy import skim\n",
- "from timeseriesflattener.testing.load_synth_data import load_synth_predictor_float\n",
- "from timeseriesflattener.resolve_multiple_functions import mean\n",
- "from timeseriesflattener.feature_spec_objects import PredictorSpec\n",
- "from pprint import pprint\n",
- "import numpy as np"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/html": [
- "<div>\n",
- "<style scoped>\n",
- " .dataframe tbody tr th:only-of-type {\n",
- " vertical-align: middle;\n",
- " }\n",
- "\n",
- " .dataframe tbody tr th {\n",
- " vertical-align: top;\n",
- " }\n",
- "\n",
- " .dataframe thead th {\n",
- " text-align: right;\n",
- " }\n",
- "</style>\n",
- "<table border=\"1\" class=\"dataframe\">\n",
- " <thead>\n",
- " <tr style=\"text-align: right;\">\n",
- " <th></th>\n",
- " <th>dw_ek_borger</th>\n",
- " <th>timestamp</th>\n",
- " <th>value</th>\n",
- " </tr>\n",
- " </thead>\n",
- " <tbody>\n",
- " <tr>\n",
- " <th>0</th>\n",
- " <td>9476</td>\n",
- " <td>1969-03-05 08:08:00</td>\n",
- " <td>0.816995</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>1</th>\n",
- " <td>4631</td>\n",
- " <td>1967-04-10 22:48:00</td>\n",
- " <td>4.818074</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>2</th>\n",
- " <td>3890</td>\n",
- " <td>1969-12-15 14:07:00</td>\n",
- " <td>2.503789</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>3</th>\n",
- " <td>1098</td>\n",
- " <td>1965-11-19 03:53:00</td>\n",
- " <td>3.515041</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>4</th>\n",
- " <td>1626</td>\n",
- " <td>1966-05-03 14:07:00</td>\n",
- " <td>4.353115</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>...</th>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>99995</th>\n",
- " <td>4542</td>\n",
- " <td>1968-06-01 17:09:00</td>\n",
- " <td>9.616722</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>99996</th>\n",
- " <td>4839</td>\n",
- " <td>1966-11-24 01:13:00</td>\n",
- " <td>0.235124</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>99997</th>\n",
- " <td>8168</td>\n",
- " <td>1969-07-30 01:45:00</td>\n",
- " <td>0.929738</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>99998</th>\n",
- " <td>9328</td>\n",
- " <td>1965-12-22 10:53:00</td>\n",
- " <td>5.124424</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>99999</th>\n",
- " <td>6582</td>\n",
- " <td>1965-02-10 09:52:00</td>\n",
- " <td>7.414466</td>\n",
- " </tr>\n",
- " </tbody>\n",
- "</table>\n",
- "<p>100000 rows × 3 columns</p>\n",
- "</div>"
- ],
- "text/plain": [
- " dw_ek_borger timestamp value\n",
- "0 9476 1969-03-05 08:08:00 0.816995\n",
- "1 4631 1967-04-10 22:48:00 4.818074\n",
- "2 3890 1969-12-15 14:07:00 2.503789\n",
- "3 1098 1965-11-19 03:53:00 3.515041\n",
- "4 1626 1966-05-03 14:07:00 4.353115\n",
- "... ... ... ...\n",
- "99995 4542 1968-06-01 17:09:00 9.616722\n",
- "99996 4839 1966-11-24 01:13:00 0.235124\n",
- "99997 8168 1969-07-30 01:45:00 0.929738\n",
- "99998 9328 1965-12-22 10:53:00 5.124424\n",
- "99999 6582 1965-02-10 09:52:00 7.414466\n",
- "\n",
- "[100000 rows x 3 columns]"
- ]
- },
- "execution_count": 2,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "pred_spec_batch = PredictorSpec(\n",
- " values_loader=load_synth_predictor_float,\n",
- " lookbehind_days=730,\n",
- " fallback=np.nan,\n",
- " resolve_multiple_fn=mean,\n",
- " feature_name=\"predictor_name\",\n",
- ")\n",
- "\n",
- "pred_spec_batch.values_df"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## The data loaders registry\n",
- "If you inspect the source code of load_synth_predictor_float, you'll see that it is decorated with @data_loaders.register(\"synth_predictor_float\")."
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "```python\n",
- "@data_loaders.register(\"synth_predictor_float\")\n",
- "def load_synth_predictor_float(\n",
- " n_rows: Optional[int] = None,\n",
- ") -> pd.DataFrame:\n",
- " \"\"\"Load synth predictor data.\".\n",
- "\n",
- " Args:\n",
- " n_rows: Number of rows to return. Defaults to None which returns entire coercion data view.\n",
- "\n",
- " Returns:\n",
- " pd.DataFrame\n",
- " \"\"\"\n",
- " return load_raw_test_csv(\"synth_raw_float_1.csv\", n_rows=n_rows)\n",
- "```"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This registers it in the data_loaders registry under the \"synth_predictor_float\" key."
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "When you initialise a feature specification, it will look at the type of its `values_loader` attribute. If its type is a string, it will look for that string as a key in the data loaders registry. If it finds it, it'll resolve it to the value, in this case the `load_synth_predictor_float` function, and call that function.\n",
- "\n",
- "The same concept applies for the resolve multiple functions.\n",
- "This is super handy if you e.g. want to parse a config file, and therefore prefer to specify your data loaders as strings."
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Creating feature combinations\n",
- "Manually specifying a handful of features one at a time is rather straightforward, but what if you want to generate hundreds of features? Or want to have multiple different lookbehind windows, e.g. a month, 6 months and a year? Then the amount of code you'll have to write will grow quite substantially and becomes time consuming and hard to navigate.\n",
- "\n",
- "To solve this problem, we implemented feature group specifications. They allow you to combinatorially create features. Let's look at an example:\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [],
- "source": [
- "from timeseriesflattener.feature_spec_objects import PredictorGroupSpec\n",
- "from timeseriesflattener.resolve_multiple_functions import maximum"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [],
- "source": [
- "pred_spec_batch = PredictorGroupSpec(\n",
- " values_loader=[\"synth_predictor_float\"],\n",
- " lookbehind_days=[365, 730],\n",
- " fallback=[np.nan],\n",
- " resolve_multiple_fn=[mean, maximum],\n",
- ").create_combinations()"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "You'll note that:\n",
- "\n",
- "1. All attributes are now required to be lists. This makes iteration easier when creating the combinations.\n",
- "2. We require values_loaders to be strings that can be resolved from the registry. This string is also used when creating the column names - otherwise we wouldn't know what to call the columns.\n",
- "\n",
- "Let's check that the results look good."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "––––––––– We created 4 combinations of predictors. ––––––––––\n",
- "[{'feature_name': 'synth_predictor_float',\n",
- " 'lookbehind_days': 365,\n",
- " 'resolve_multiple_fn': 'mean'},\n",
- " {'feature_name': 'synth_predictor_float',\n",
- " 'lookbehind_days': 730,\n",
- " 'resolve_multiple_fn': 'mean'},\n",
- " {'feature_name': 'synth_predictor_float',\n",
- " 'lookbehind_days': 365,\n",
- " 'resolve_multiple_fn': 'maximum'},\n",
- " {'feature_name': 'synth_predictor_float',\n",
- " 'lookbehind_days': 730,\n",
- " 'resolve_multiple_fn': 'maximum'}]\n"
- ]
- }
- ],
- "source": [
- "# Create a small summary to highlight the generated predictors\n",
- "pred_spec_batch_summary = [\n",
- " {\n",
- " \"feature_name\": pred_spec.feature_name,\n",
- " \"lookbehind_days\": pred_spec.lookbehind_days,\n",
- " \"resolve_multiple_fn\": pred_spec.key_for_resolve_multiple,\n",
- " }\n",
- " for pred_spec in pred_spec_batch\n",
- "]\n",
- "print(\n",
- " f\"––––––––– We created {len(pred_spec_batch)} combinations of predictors. ––––––––––\"\n",
- ")\n",
- "pprint(pred_spec_batch_summary)"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Now we know how to create a bunch of feature specifications quickly! But with more features comes more computation. Let's look at caching next, so we can iterate on our datasets more quickly."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# Caching"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Timeseriesflattener ships with a class that allows for caching to disk. Let's look at an example of that:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [],
- "source": [
- "from skimpy import skim\n",
- "from timeseriesflattener.testing.load_synth_data import load_synth_prediction_times\n",
- "from timeseriesflattener.feature_cache.cache_to_disk import DiskCache\n",
- "from timeseriesflattener.flattened_dataset import TimeseriesFlattener\n",
- "from pathlib import Path"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {},
- "outputs": [],
- "source": [
- "ts_flattener = TimeseriesFlattener(\n",
- " prediction_times_df=load_synth_prediction_times(),\n",
- " id_col_name=\"dw_ek_borger\",\n",
- " timestamp_col_name=\"timestamp\",\n",
- " n_workers=4,\n",
- " cache=DiskCache(feature_cache_dir=Path(\".tmp\") / \"feature_cache\"),\n",
- " drop_pred_times_with_insufficient_look_distance=True,\n",
- ")"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "All we need to specify is that we use the DiskCache class, and which directory to save the feature cache to.\n",
- "\n",
- "The first time we create features, this will just save them to disk and won't make any difference to performance. But say we want to add two more features - then it'll load the features that it has already computed from disk, and then only compute the two new features.\n",
- "\n",
- "Note that DiskCache is an instance of the abstract class FeatureCache. If you want to implement your own cache, for example using REDIS or SQL, all you'll need is to implement the 3 methods in that class. Now, let's compute a dataframe to check that everything works."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [],
- "source": [
- "ts_flattener.add_spec(pred_spec_batch)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 9,
- "metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "2022-12-08 14:14:12 [INFO] There were unprocessed specs, computing...\n",
- "2022-12-08 14:14:12 [INFO] _drop_pred_time_if_insufficient_look_distance: Dropped 4038 (0.4%) rows\n",
- "100%|██████████| 4/4 [00:01<00:00, 3.08it/s]\n",
- "2022-12-08 14:14:13 [INFO] Starting concatenation. Will take some time on performant systems, e.g. 30s for 100 features. This is normal.\n",
- "2022-12-08 14:14:13 [INFO] Concatenation took 0.018 seconds\n",
- "2022-12-08 14:14:13 [INFO] Merging with original df\n"
- ]
- }
- ],
- "source": [
- "df = ts_flattener.get_df()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 10,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/html": [
- "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">╭──────────────────────────────────────────────── skimpy summary ─────────────────────────────────────────────────╮\n",
- "│ <span style=\"font-style: italic\"> Data Summary </span> <span style=\"font-style: italic\"> Data Types </span> │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ │\n",
- "│ ┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> dataframe </span>┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Values </span>┃ ┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Column Type </span>┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Count </span>┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ │\n",
- "│ │ Number of rows │ 5962 │ │ float64 │ 4 │ │\n",
- "│ │ Number of columns │ 7 │ │ int64 │ 1 │ │\n",
- "│ └───────────────────┴────────┘ │ datetime64 │ 1 │ │\n",
- "│ │ string │ 1 │ │\n",
- "│ └─────────────┴───────┘ │\n",
- "│ <span style=\"font-style: italic\"> number </span> │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
- "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">dw_ek_borger </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7400</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█▇███▇ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 820</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 14</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.00039</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 4.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 8.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▂▃▄▆█ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 820</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 14</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.00039</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.4</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▂▄██▄▂ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 110</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7.7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.058</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.3</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ▁▁▂▄█ </span> │ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 110</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.058</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.9</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.9</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▃██▃▁ </span> │ │\n",
- "│ └───────────────────────────┴───────┴────────┴────────┴───────┴───────────┴───────┴───────┴────────┴─────────┘ │\n",
- "│ <span style=\"font-style: italic\"> datetime </span> │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
- "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> first </span>┃<span style=\"font-weight: bold\"> last </span>┃<span style=\"font-weight: bold\"> frequency </span>┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">timestamp </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1967-01-02 01:16:00 </span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1969-12-31 21:42:00 </span> │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">None </span> │ │\n",
- "│ └──────────────────┴──────┴─────────┴────────────────────────────┴────────────────────────────┴──────────────┘ │\n",
- "│ <span style=\"font-style: italic\"> string </span> │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓ │\n",
- "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> words per row </span>┃<span style=\"font-weight: bold\"> total words </span>┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩ │\n",
- "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">prediction_time_uuid </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6000</span> │ │\n",
- "│ └───────────────────────────────────────┴───────┴───────────┴──────────────────────────┴─────────────────────┘ │\n",
- "╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯\n",
- "</pre>\n"
- ],
- "text/plain": [
- "╭──────────────────────────────────────────────── skimpy summary ─────────────────────────────────────────────────╮\n",
- "│ \u001b[3m Data Summary \u001b[0m \u001b[3m Data Types \u001b[0m │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ │\n",
- "│ ┃\u001b[1;36m \u001b[0m\u001b[1;36mdataframe \u001b[0m\u001b[1;36m \u001b[0m┃\u001b[1;36m \u001b[0m\u001b[1;36mValues\u001b[0m\u001b[1;36m \u001b[0m┃ ┃\u001b[1;36m \u001b[0m\u001b[1;36mColumn Type\u001b[0m\u001b[1;36m \u001b[0m┃\u001b[1;36m \u001b[0m\u001b[1;36mCount\u001b[0m\u001b[1;36m \u001b[0m┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ │\n",
- "│ │ Number of rows │ 5962 │ │ float64 │ 4 │ │\n",
- "│ │ Number of columns │ 7 │ │ int64 │ 1 │ │\n",
- "│ └───────────────────┴────────┘ │ datetime64 │ 1 │ │\n",
- "│ │ string │ 1 │ │\n",
- "│ └─────────────┴───────┘ │\n",
- "│ \u001b[3m number \u001b[0m │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
- "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mdw_ek_borger \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7400\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m█▇███▇ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 820\u001b[0m │ \u001b[36m 14\u001b[0m │ \u001b[36m 6.6\u001b[0m │ \u001b[36m 2.6\u001b[0m │ \u001b[36m 0.00039\u001b[0m │ \u001b[36m 4.8\u001b[0m │ \u001b[36m 8.8\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m▁▂▃▄▆█ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 820\u001b[0m │ \u001b[36m 14\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 2.1\u001b[0m │ \u001b[36m 0.00039\u001b[0m │ \u001b[36m 3.5\u001b[0m │ \u001b[36m 6.4\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m▂▄██▄▂ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 110\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 7.7\u001b[0m │ \u001b[36m 2.1\u001b[0m │ \u001b[36m 0.058\u001b[0m │ \u001b[36m 6.7\u001b[0m │ \u001b[36m 9.3\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m ▁▁▂▄█ \u001b[0m │ │\n",
- "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 110\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 1.7\u001b[0m │ \u001b[36m 0.058\u001b[0m │ \u001b[36m 3.9\u001b[0m │ \u001b[36m 6.1\u001b[0m │ \u001b[36m 9.9\u001b[0m │ \u001b[32m▁▃██▃▁ \u001b[0m │ │\n",
- "│ └───────────────────────────┴───────┴────────┴────────┴───────┴───────────┴───────┴───────┴────────┴─────────┘ │\n",
- "│ \u001b[3m datetime \u001b[0m │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
- "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mfirst \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mlast \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mfrequency \u001b[0m\u001b[1m \u001b[0m┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mtimestamp \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[31m 1967-01-02 01:16:00 \u001b[0m │ \u001b[31m 1969-12-31 21:42:00 \u001b[0m │ \u001b[38;5;141mNone \u001b[0m │ │\n",
- "│ └──────────────────┴──────┴─────────┴────────────────────────────┴────────────────────────────┴──────────────┘ │\n",
- "│ \u001b[3m string \u001b[0m │\n",
- "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓ │\n",
- "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mwords per row \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mtotal words \u001b[0m\u001b[1m \u001b[0m┃ │\n",
- "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩ │\n",
- "│ │ \u001b[38;5;141mprediction_time_uuid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 6000\u001b[0m │ │\n",
- "│ └───────────────────────────────────────┴───────┴───────────┴──────────────────────────┴─────────────────────┘ │\n",
- "╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯\n"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
+ "cells": [{
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the basic tutorial we covered how to add static features, predictors and outcomes.\n",
+ "In this tutorial, we'll expand on that, covering how to effectively add many features by:\n",
+ "1. Utilising data loaders in a data_loaders registry,\n",
+ "2. Populating a dictionary from a long format dataframe,\n",
+ "3. Creating feature combinations from specifcations,\n",
+ "4. Using caching, so you can iterate on your datasets without having to complete full computations every time\n"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Using data loaders\n",
+ "Until now, we've loaded our data first and then created combinations. But what if your data lies in an SQL database, and you don't want to save it to disk?\n",
+ "\n",
+ "Time to introduce feature loaders. All feature spec objects can resolve from a loader function. The only requirement of that loader function is that it should return a values dataframe, which should contain an ID column, a timestamp column and a list of vlaues. This means you can have loaders that load from REDIS, SQL databases, or just from disk. Whatever you prefer.\n",
+ "\n",
+ "This function is then called when you initialise a specification.\n",
+ "\n",
+ "This loader is specified in the values_loader key like so:\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from skimpy import skim\n",
+ "from timeseriesflattener.testing.load_synth_data import load_synth_predictor_float\n",
+ "from timeseriesflattener.resolve_multiple_functions import mean\n",
+ "from timeseriesflattener.feature_spec_objects import PredictorSpec\n",
+ "from pprint import pprint\n",
+ "import numpy as np"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [{
+ "data": {
+ "text/html": [
+ "<div>\n",
+ "<style scoped>\n",
+ " .dataframe tbody tr th:only-of-type {\n",
+ " vertical-align: middle;\n",
+ " }\n",
+ "\n",
+ " .dataframe tbody tr th {\n",
+ " vertical-align: top;\n",
+ " }\n",
+ "\n",
+ " .dataframe thead th {\n",
+ " text-align: right;\n",
+ " }\n",
+ "</style>\n",
+ "<table border=\"1\" class=\"dataframe\">\n",
+ " <thead>\n",
+ " <tr style=\"text-align: right;\">\n",
+ " <th></th>\n",
+ " <th>id</th>\n",
+ " <th>timestamp</th>\n",
+ " <th>value</th>\n",
+ " </tr>\n",
+ " </thead>\n",
+ " <tbody>\n",
+ " <tr>\n",
+ " <th>0</th>\n",
+ " <td>9476</td>\n",
+ " <td>1969-03-05 08:08:00</td>\n",
+ " <td>0.816995</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>1</th>\n",
+ " <td>4631</td>\n",
+ " <td>1967-04-10 22:48:00</td>\n",
+ " <td>4.818074</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2</th>\n",
+ " <td>3890</td>\n",
+ " <td>1969-12-15 14:07:00</td>\n",
+ " <td>2.503789</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>3</th>\n",
+ " <td>1098</td>\n",
+ " <td>1965-11-19 03:53:00</td>\n",
+ " <td>3.515041</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>4</th>\n",
+ " <td>1626</td>\n",
+ " <td>1966-05-03 14:07:00</td>\n",
+ " <td>4.353115</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>...</th>\n",
+ " <td>...</td>\n",
+ " <td>...</td>\n",
+ " <td>...</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>99995</th>\n",
+ " <td>4542</td>\n",
+ " <td>1968-06-01 17:09:00</td>\n",
+ " <td>9.616722</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>99996</th>\n",
+ " <td>4839</td>\n",
+ " <td>1966-11-24 01:13:00</td>\n",
+ " <td>0.235124</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>99997</th>\n",
+ " <td>8168</td>\n",
+ " <td>1969-07-30 01:45:00</td>\n",
+ " <td>0.929738</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>99998</th>\n",
+ " <td>9328</td>\n",
+ " <td>1965-12-22 10:53:00</td>\n",
+ " <td>5.124424</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>99999</th>\n",
+ " <td>6582</td>\n",
+ " <td>1965-02-10 09:52:00</td>\n",
+ " <td>7.414466</td>\n",
+ " </tr>\n",
+ " </tbody>\n",
+ "</table>\n",
+ "<p>100000 rows × 3 columns</p>\n",
+ "</div>"
+ ],
+ "text/plain": [
+ " id timestamp value\n",
+ "0 9476 1969-03-05 08:08:00 0.816995\n",
+ "1 4631 1967-04-10 22:48:00 4.818074\n",
+ "2 3890 1969-12-15 14:07:00 2.503789\n",
+ "3 1098 1965-11-19 03:53:00 3.515041\n",
+ "4 1626 1966-05-03 14:07:00 4.353115\n",
+ "... ... ... ...\n",
+ "99995 4542 1968-06-01 17:09:00 9.616722\n",
+ "99996 4839 1966-11-24 01:13:00 0.235124\n",
+ "99997 8168 1969-07-30 01:45:00 0.929738\n",
+ "99998 9328 1965-12-22 10:53:00 5.124424\n",
+ "99999 6582 1965-02-10 09:52:00 7.414466\n",
+ "\n",
+ "[100000 rows x 3 columns]"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }],
+ "source": [
+ "pred_spec_batch = PredictorSpec(\n",
+ " values_loader=load_synth_predictor_float,\n",
+ " lookbehind_days=730,\n",
+ " fallback=np.nan,\n",
+ " resolve_multiple_fn=mean,\n",
+ " feature_name=\"predictor_name\",\n",
+ ")\n",
+ "\n",
+ "pred_spec_batch.values_df"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The data loaders registry\n",
+ "If you inspect the source code of load_synth_predictor_float, you'll see that it is decorated with @data_loaders.register(\"synth_predictor_float\")."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```python\n",
+ "@data_loaders.register(\"synth_predictor_float\")\n",
+ "def load_synth_predictor_float(\n",
+ " n_rows: Optional[int] = None,\n",
+ ") -> pd.DataFrame:\n",
+ " \"\"\"Load synth predictor data.\".\n",
+ "\n",
+ " Args:\n",
+ " n_rows: Number of rows to return. Defaults to None which returns entire coercion data view.\n",
+ "\n",
+ " Returns:\n",
+ " pd.DataFrame\n",
+ " \"\"\"\n",
+ " return load_raw_test_csv(\"synth_raw_float_1.csv\", n_rows=n_rows)\n",
+ "```"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This registers it in the data_loaders registry under the \"synth_predictor_float\" key."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When you initialise a feature specification, it will look at the type of its `values_loader` attribute. If its type is a string, it will look for that string as a key in the data loaders registry. If it finds it, it'll resolve it to the value, in this case the `load_synth_predictor_float` function, and call that function.\n",
+ "\n",
+ "The same concept applies for the resolve multiple functions.\n",
+ "This is super handy if you e.g. want to parse a config file, and therefore prefer to specify your data loaders as strings."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Creating feature combinations\n",
+ "Manually specifying a handful of features one at a time is rather straightforward, but what if you want to generate hundreds of features? Or want to have multiple different lookbehind windows, e.g. a month, 6 months and a year? Then the amount of code you'll have to write will grow quite substantially and becomes time consuming and hard to navigate.\n",
+ "\n",
+ "To solve this problem, we implemented feature group specifications. They allow you to combinatorially create features. Let's look at an example:\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from timeseriesflattener.feature_spec_objects import PredictorGroupSpec\n",
+ "from timeseriesflattener.resolve_multiple_functions import maximum"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "pred_spec_batch = PredictorGroupSpec(\n",
+ " values_loader=[\"synth_predictor_float\"],\n",
+ " lookbehind_days=[365, 730],\n",
+ " fallback=[np.nan],\n",
+ " resolve_multiple_fn=[mean, maximum],\n",
+ ").create_combinations()"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You'll note that:\n",
+ "\n",
+ "1. All attributes are now required to be lists. This makes iteration easier when creating the combinations.\n",
+ "2. We require values_loaders to be strings that can be resolved from the registry. This string is also used when creating the column names - otherwise we wouldn't know what to call the columns.\n",
+ "\n",
+ "Let's check that the results look good."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [{
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "––––––––– We created 4 combinations of predictors. ––––––––––\n",
+ "[{'feature_name': 'synth_predictor_float',\n",
+ " 'lookbehind_days': 365,\n",
+ " 'resolve_multiple_fn': 'mean'},\n",
+ " {'feature_name': 'synth_predictor_float',\n",
+ " 'lookbehind_days': 730,\n",
+ " 'resolve_multiple_fn': 'mean'},\n",
+ " {'feature_name': 'synth_predictor_float',\n",
+ " 'lookbehind_days': 365,\n",
+ " 'resolve_multiple_fn': 'maximum'},\n",
+ " {'feature_name': 'synth_predictor_float',\n",
+ " 'lookbehind_days': 730,\n",
+ " 'resolve_multiple_fn': 'maximum'}]\n"
+ ]
+ }],
+ "source": [
+ "# Create a small summary to highlight the generated predictors\n",
+ "pred_spec_batch_summary = [\n",
+ " {\n",
+ " \"feature_name\": pred_spec.feature_name,\n",
+ " \"lookbehind_days\": pred_spec.lookbehind_days,\n",
+ " \"resolve_multiple_fn\": pred_spec.key_for_resolve_multiple,\n",
+ " }\n",
+ " for pred_spec in pred_spec_batch\n",
+ "]\n",
+ "print(\n",
+ " f\"––––––––– We created {len(pred_spec_batch)} combinations of predictors. ––––––––––\"\n",
+ ")\n",
+ "pprint(pred_spec_batch_summary)"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we know how to create a bunch of feature specifications quickly! But with more features comes more computation. Let's look at caching next, so we can iterate on our datasets more quickly."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Caching"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Timeseriesflattener ships with a class that allows for caching to disk. Let's look at an example of that:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from skimpy import skim\n",
+ "from timeseriesflattener.testing.load_synth_data import load_synth_prediction_times\n",
+ "from timeseriesflattener.feature_cache.cache_to_disk import DiskCache\n",
+ "from timeseriesflattener.flattened_dataset import TimeseriesFlattener\n",
+ "from pathlib import Path"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ts_flattener = TimeseriesFlattener(\n",
+ " prediction_times_df=load_synth_prediction_times(),\n",
+ " id_col_name=\"id\",\n",
+ " timestamp_col_name=\"timestamp\",\n",
+ " n_workers=4,\n",
+ " cache=DiskCache(feature_cache_dir=Path(\".tmp\") / \"feature_cache\"),\n",
+ " drop_pred_times_with_insufficient_look_distance=True,\n",
+ ")"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "All we need to specify is that we use the DiskCache class, and which directory to save the feature cache to.\n",
+ "\n",
+ "The first time we create features, this will just save them to disk and won't make any difference to performance. But say we want to add two more features - then it'll load the features that it has already computed from disk, and then only compute the two new features.\n",
+ "\n",
+ "Note that DiskCache is an instance of the abstract class FeatureCache. If you want to implement your own cache, for example using REDIS or SQL, all you'll need is to implement the 3 methods in that class. Now, let's compute a dataframe to check that everything works."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ts_flattener.add_spec(pred_spec_batch)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [{
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "2022-12-08 14:14:12 [INFO] There were unprocessed specs, computing...\n",
+ "2022-12-08 14:14:12 [INFO] _drop_pred_time_if_insufficient_look_distance: Dropped 4038 (0.4%) rows\n",
+ "100%|██████████| 4/4 [00:01<00:00, 3.08it/s]\n",
+ "2022-12-08 14:14:13 [INFO] Starting concatenation. Will take some time on performant systems, e.g. 30s for 100 features. This is normal.\n",
+ "2022-12-08 14:14:13 [INFO] Concatenation took 0.018 seconds\n",
+ "2022-12-08 14:14:13 [INFO] Merging with original df\n"
+ ]
+ }],
+ "source": [
+ "df = ts_flattener.get_df()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [{
+ "data": {
+ "text/html": [
+ "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">╭──────────────────────────────────────────────── skimpy summary ─────────────────────────────────────────────────╮\n",
+ "│ <span style=\"font-style: italic\"> Data Summary </span> <span style=\"font-style: italic\"> Data Types </span> │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ │\n",
+ "│ ┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> dataframe </span>┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Values </span>┃ ┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Column Type </span>┃<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\"> Count </span>┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ │\n",
+ "│ │ Number of rows │ 5962 │ │ float64 │ 4 │ │\n",
+ "│ │ Number of columns │ 7 │ │ int64 │ 1 │ │\n",
+ "│ └───────────────────┴────────┘ │ datetime64 │ 1 │ │\n",
+ "│ │ string │ 1 │ │\n",
+ "│ └─────────────┴───────┘ │\n",
+ "│ <span style=\"font-style: italic\"> number </span> │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
+ "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> mean </span>┃<span style=\"font-weight: bold\"> sd </span>┃<span style=\"font-weight: bold\"> p0 </span>┃<span style=\"font-weight: bold\"> p25 </span>┃<span style=\"font-weight: bold\"> p75 </span>┃<span style=\"font-weight: bold\"> p100 </span>┃<span style=\"font-weight: bold\"> hist </span>┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">id </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5000</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2900</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2500</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7400</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10000</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">█▇███▇ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 820</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 14</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.6</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.00039</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 4.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 8.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▂▃▄▆█ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 820</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 14</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.00039</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.4</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▂▄██▄▂ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 110</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 7.7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 2.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.058</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.3</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 10</span> │ <span style=\"color: #008000; text-decoration-color: #008000\"> ▁▁▂▄█ </span> │ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">pred_synth_predictor </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 110</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.8</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 5</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1.7</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0.058</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 3.9</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6.1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 9.9</span> │ <span style=\"color: #008000; text-decoration-color: #008000\">▁▃██▃▁ </span> │ │\n",
+ "│ └───────────────────────────┴───────┴────────┴────────┴───────┴───────────┴───────┴───────┴────────┴─────────┘ │\n",
+ "│ <span style=\"font-style: italic\"> datetime </span> │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
+ "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> first </span>┃<span style=\"font-weight: bold\"> last </span>┃<span style=\"font-weight: bold\"> frequency </span>┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">timestamp </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1967-01-02 01:16:00 </span> │ <span style=\"color: #800000; text-decoration-color: #800000\"> 1969-12-31 21:42:00 </span> │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">None </span> │ │\n",
+ "│ └──────────────────┴──────┴─────────┴────────────────────────────┴────────────────────────────┴──────────────┘ │\n",
+ "│ <span style=\"font-style: italic\"> string </span> │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓ │\n",
+ "│ ┃<span style=\"font-weight: bold\"> column_name </span>┃<span style=\"font-weight: bold\"> NA </span>┃<span style=\"font-weight: bold\"> NA % </span>┃<span style=\"font-weight: bold\"> words per row </span>┃<span style=\"font-weight: bold\"> total words </span>┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩ │\n",
+ "│ │ <span style=\"color: #af87ff; text-decoration-color: #af87ff\">prediction_time_uuid </span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 0</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 1</span> │ <span style=\"color: #008080; text-decoration-color: #008080\"> 6000</span> │ │\n",
+ "│ └───────────────────────────────────────┴───────┴───────────┴──────────────────────────┴─────────────────────┘ │\n",
+ "╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯\n",
+ "</pre>\n"
+ ],
+ "text/plain": [
+ "╭──────────────────────────────────────────────── skimpy summary ─────────────────────────────────────────────────╮\n",
+ "│ \u001b[3m Data Summary \u001b[0m \u001b[3m Data Types \u001b[0m │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┓ ┏━━━━━━━━━━━━━┳━━━━━━━┓ │\n",
+ "│ ┃\u001b[1;36m \u001b[0m\u001b[1;36mdataframe \u001b[0m\u001b[1;36m \u001b[0m┃\u001b[1;36m \u001b[0m\u001b[1;36mValues\u001b[0m\u001b[1;36m \u001b[0m┃ ┃\u001b[1;36m \u001b[0m\u001b[1;36mColumn Type\u001b[0m\u001b[1;36m \u001b[0m┃\u001b[1;36m \u001b[0m\u001b[1;36mCount\u001b[0m\u001b[1;36m \u001b[0m┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━╇━━━━━━━━┩ ┡━━━━━━━━━━━━━╇━━━━━━━┩ │\n",
+ "│ │ Number of rows │ 5962 │ │ float64 │ 4 │ │\n",
+ "│ │ Number of columns │ 7 │ │ int64 │ 1 │ │\n",
+ "│ └───────────────────┴────────┘ │ datetime64 │ 1 │ │\n",
+ "│ │ string │ 1 │ │\n",
+ "│ └─────────────┴───────┘ │\n",
+ "│ \u001b[3m number \u001b[0m │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━━┳━━━━━━━━━┓ │\n",
+ "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mmean \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1msd \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp0 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp25 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp75 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mp100 \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mhist \u001b[0m\u001b[1m \u001b[0m┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━╇━━━━━━━╇━━━━━━━━╇━━━━━━━━━┩ │\n",
+ "│ │ \u001b[38;5;141mid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 5000\u001b[0m │ \u001b[36m 2900\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 2500\u001b[0m │ \u001b[36m 7400\u001b[0m │ \u001b[36m 10000\u001b[0m │ \u001b[32m█▇███▇ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 820\u001b[0m │ \u001b[36m 14\u001b[0m │ \u001b[36m 6.6\u001b[0m │ \u001b[36m 2.6\u001b[0m │ \u001b[36m 0.00039\u001b[0m │ \u001b[36m 4.8\u001b[0m │ \u001b[36m 8.8\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m▁▂▃▄▆█ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 820\u001b[0m │ \u001b[36m 14\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 2.1\u001b[0m │ \u001b[36m 0.00039\u001b[0m │ \u001b[36m 3.5\u001b[0m │ \u001b[36m 6.4\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m▂▄██▄▂ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 110\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 7.7\u001b[0m │ \u001b[36m 2.1\u001b[0m │ \u001b[36m 0.058\u001b[0m │ \u001b[36m 6.7\u001b[0m │ \u001b[36m 9.3\u001b[0m │ \u001b[36m 10\u001b[0m │ \u001b[32m ▁▁▂▄█ \u001b[0m │ │\n",
+ "│ │ \u001b[38;5;141mpred_synth_predictor \u001b[0m │ \u001b[36m 110\u001b[0m │ \u001b[36m 1.8\u001b[0m │ \u001b[36m 5\u001b[0m │ \u001b[36m 1.7\u001b[0m │ \u001b[36m 0.058\u001b[0m │ \u001b[36m 3.9\u001b[0m │ \u001b[36m 6.1\u001b[0m │ \u001b[36m 9.9\u001b[0m │ \u001b[32m▁▃██▃▁ \u001b[0m │ │\n",
+ "│ └───────────────────────────┴───────┴────────┴────────┴───────┴───────────┴───────┴───────┴────────┴─────────┘ │\n",
+ "│ \u001b[3m datetime \u001b[0m │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━┳━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ │\n",
+ "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mfirst \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mlast \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mfrequency \u001b[0m\u001b[1m \u001b[0m┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━╇━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ │\n",
+ "│ │ \u001b[38;5;141mtimestamp \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[31m 1967-01-02 01:16:00 \u001b[0m │ \u001b[31m 1969-12-31 21:42:00 \u001b[0m │ \u001b[38;5;141mNone \u001b[0m │ │\n",
+ "│ └──────────────────┴──────┴─────────┴────────────────────────────┴────────────────────────────┴──────────────┘ │\n",
+ "│ \u001b[3m string \u001b[0m │\n",
+ "│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓ │\n",
+ "│ ┃\u001b[1m \u001b[0m\u001b[1mcolumn_name \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mNA % \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mwords per row \u001b[0m\u001b[1m \u001b[0m┃\u001b[1m \u001b[0m\u001b[1mtotal words \u001b[0m\u001b[1m \u001b[0m┃ │\n",
+ "│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩ │\n",
+ "│ │ \u001b[38;5;141mprediction_time_uuid \u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 0\u001b[0m │ \u001b[36m 1\u001b[0m │ \u001b[36m 6000\u001b[0m │ │\n",
+ "│ └───────────────────────────────────────┴───────┴───────────┴──────────────────────────┴─────────────────────┘ │\n",
+ "╰────────────────────────────────────────────────────── End ──────────────────────────────────────────────────────╯\n"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "data": {
+ "text/html": [
+ "<div>\n",
+ "<style scoped>\n",
+ " .dataframe tbody tr th:only-of-type {\n",
+ " vertical-align: middle;\n",
+ " }\n",
+ "\n",
+ " .dataframe tbody tr th {\n",
+ " vertical-align: top;\n",
+ " }\n",
+ "\n",
+ " .dataframe thead th {\n",
+ " text-align: right;\n",
+ " }\n",
+ "</style>\n",
+ "<table border=\"1\" class=\"dataframe\">\n",
+ " <thead>\n",
+ " <tr style=\"text-align: right;\">\n",
+ " <th></th>\n",
+ " <th>id</th>\n",
+ " <th>timestamp</th>\n",
+ " <th>prediction_time_uuid</th>\n",
+ " <th>pred_synth_predictor_float_within_365_days_maximum_fallback_nan</th>\n",
+ " <th>pred_synth_predictor_float_within_365_days_mean_fallback_nan</th>\n",
+ " <th>pred_synth_predictor_float_within_730_days_maximum_fallback_nan</th>\n",
+ " <th>pred_synth_predictor_float_within_730_days_mean_fallback_nan</th>\n",
+ " </tr>\n",
+ " </thead>\n",
+ " <tbody>\n",
+ " <tr>\n",
+ " <th>0</th>\n",
+ " <td>9903</td>\n",
+ " <td>1968-05-09 21:24:00</td>\n",
+ " <td>9903-1968-05-09-21-24-00</td>\n",
+ " <td>0.154981</td>\n",
+ " <td>0.154981</td>\n",
+ " <td>2.194319</td>\n",
+ " <td>0.990763</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>1</th>\n",
+ " <td>6447</td>\n",
+ " <td>1967-09-25 18:08:00</td>\n",
+ " <td>6447-1967-09-25-18-08-00</td>\n",
+ " <td>8.930256</td>\n",
+ " <td>5.396017</td>\n",
+ " <td>9.774050</td>\n",
+ " <td>5.582745</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>2</th>\n",
+ " <td>4927</td>\n",
+ " <td>1968-06-30 12:13:00</td>\n",
+ " <td>4927-1968-06-30-12-13-00</td>\n",
+ " <td>6.730694</td>\n",
+ " <td>4.957251</td>\n",
+ " <td>6.730694</td>\n",
+ " <td>4.957251</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>3</th>\n",
+ " <td>5475</td>\n",
+ " <td>1967-01-09 03:09:00</td>\n",
+ " <td>5475-1967-01-09-03-09-00</td>\n",
+ " <td>9.497229</td>\n",
+ " <td>6.081539</td>\n",
+ " <td>9.497229</td>\n",
+ " <td>5.999336</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>4</th>\n",
+ " <td>3157</td>\n",
+ " <td>1969-10-07 05:01:00</td>\n",
+ " <td>3157-1969-10-07-05-01-00</td>\n",
+ " <td>5.243176</td>\n",
+ " <td>5.068323</td>\n",
+ " <td>5.243176</td>\n",
+ " <td>5.068323</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>...</th>\n",
+ " <td>...</td>\n",
+ " <td>...</td>\n",
+ " <td>...</td>\n",
+ " <td>...</td>\n",
+ " <td>...</td>\n",
+ " <td>...</td>\n",
+ " <td>...</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>5957</th>\n",
+ " <td>4228</td>\n",
+ " <td>1967-02-26 05:45:00</td>\n",
+ " <td>4228-1967-02-26-05-45-00</td>\n",
+ " <td>6.844010</td>\n",
+ " <td>4.353579</td>\n",
+ " <td>6.844010</td>\n",
+ " <td>3.792014</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>5958</th>\n",
+ " <td>9745</td>\n",
+ " <td>1969-02-04 01:18:00</td>\n",
+ " <td>9745-1969-02-04-01-18-00</td>\n",
+ " <td>3.858509</td>\n",
+ " <td>3.858509</td>\n",
+ " <td>3.858509</td>\n",
+ " <td>2.394074</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>5959</th>\n",
+ " <td>3385</td>\n",
+ " <td>1967-07-17 19:18:00</td>\n",
+ " <td>3385-1967-07-17-19-18-00</td>\n",
+ " <td>9.370554</td>\n",
+ " <td>5.463267</td>\n",
+ " <td>9.370554</td>\n",
+ " <td>5.769484</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>5960</th>\n",
+ " <td>1421</td>\n",
+ " <td>1968-04-15 15:53:00</td>\n",
+ " <td>1421-1968-04-15-15-53-00</td>\n",
+ " <td>8.972364</td>\n",
+ " <td>8.972364</td>\n",
+ " <td>8.972364</td>\n",
+ " <td>7.732447</td>\n",
+ " </tr>\n",
+ " <tr>\n",
+ " <th>5961</th>\n",
+ " <td>1940</td>\n",
+ " <td>1968-05-17 10:49:00</td>\n",
+ " <td>1940-1968-05-17-10-49-00</td>\n",
+ " <td>NaN</td>\n",
+ " <td>NaN</td>\n",
+ " <td>7.448374</td>\n",
+ " <td>4.846514</td>\n",
+ " </tr>\n",
+ " </tbody>\n",
+ "</table>\n",
+ "<p>5962 rows × 7 columns</p>\n",
+ "</div>"
+ ],
+ "text/plain": [
+ " id timestamp prediction_time_uuid \\\n",
+ "0 9903 1968-05-09 21:24:00 9903-1968-05-09-21-24-00 \n",
+ "1 6447 1967-09-25 18:08:00 6447-1967-09-25-18-08-00 \n",
+ "2 4927 1968-06-30 12:13:00 4927-1968-06-30-12-13-00 \n",
+ "3 5475 1967-01-09 03:09:00 5475-1967-01-09-03-09-00 \n",
+ "4 3157 1969-10-07 05:01:00 3157-1969-10-07-05-01-00 \n",
+ "... ... ... ... \n",
+ "5957 4228 1967-02-26 05:45:00 4228-1967-02-26-05-45-00 \n",
+ "5958 9745 1969-02-04 01:18:00 9745-1969-02-04-01-18-00 \n",
+ "5959 3385 1967-07-17 19:18:00 3385-1967-07-17-19-18-00 \n",
+ "5960 1421 1968-04-15 15:53:00 1421-1968-04-15-15-53-00 \n",
+ "5961 1940 1968-05-17 10:49:00 1940-1968-05-17-10-49-00 \n",
+ "\n",
+ " pred_synth_predictor_float_within_365_days_maximum_fallback_nan \\\n",
+ "0 0.154981 \n",
+ "1 8.930256 \n",
+ "2 6.730694 \n",
+ "3 9.497229 \n",
+ "4 5.243176 \n",
+ "... ... \n",
+ "5957 6.844010 \n",
+ "5958 3.858509 \n",
+ "5959 9.370554 \n",
+ "5960 8.972364 \n",
+ "5961 NaN \n",
+ "\n",
+ " pred_synth_predictor_float_within_365_days_mean_fallback_nan \\\n",
+ "0 0.154981 \n",
+ "1 5.396017 \n",
+ "2 4.957251 \n",
+ "3 6.081539 \n",
+ "4 5.068323 \n",
+ "... ... \n",
+ "5957 4.353579 \n",
+ "5958 3.858509 \n",
+ "5959 5.463267 \n",
+ "5960 8.972364 \n",
+ "5961 NaN \n",
+ "\n",
+ " pred_synth_predictor_float_within_730_days_maximum_fallback_nan \\\n",
+ "0 2.194319 \n",
+ "1 9.774050 \n",
+ "2 6.730694 \n",
+ "3 9.497229 \n",
+ "4 5.243176 \n",
+ "... ... \n",
+ "5957 6.844010 \n",
+ "5958 3.858509 \n",
+ "5959 9.370554 \n",
+ "5960 8.972364 \n",
+ "5961 7.448374 \n",
+ "\n",
+ " pred_synth_predictor_float_within_730_days_mean_fallback_nan \n",
+ "0 0.990763 \n",
+ "1 5.582745 \n",
+ "2 4.957251 \n",
+ "3 5.999336 \n",
+ "4 5.068323 \n",
+ "... ... \n",
+ "5957 3.792014 \n",
+ "5958 2.394074 \n",
+ "5959 5.769484 \n",
+ "5960 7.732447 \n",
+ "5961 4.846514 \n",
+ "\n",
+ "[5962 rows x 7 columns]"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "skim(df)\n",
+ "df"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3.10.7 ('.venv': poetry)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.7"
+ },
+ "orig_nbformat": 4,
+ "vscode": {
+ "interpreter": {
+ "hash": "d2b49c0af2d95979144de75823f7cfbb268839811992fdd0cb17fc1bb54ce815"
+ }
+ }
},
- {
- "data": {
- "text/html": [
- "<div>\n",
- "<style scoped>\n",
- " .dataframe tbody tr th:only-of-type {\n",
- " vertical-align: middle;\n",
- " }\n",
- "\n",
- " .dataframe tbody tr th {\n",
- " vertical-align: top;\n",
- " }\n",
- "\n",
- " .dataframe thead th {\n",
- " text-align: right;\n",
- " }\n",
- "</style>\n",
- "<table border=\"1\" class=\"dataframe\">\n",
- " <thead>\n",
- " <tr style=\"text-align: right;\">\n",
- " <th></th>\n",
- " <th>dw_ek_borger</th>\n",
- " <th>timestamp</th>\n",
- " <th>prediction_time_uuid</th>\n",
- " <th>pred_synth_predictor_float_within_365_days_maximum_fallback_nan</th>\n",
- " <th>pred_synth_predictor_float_within_365_days_mean_fallback_nan</th>\n",
- " <th>pred_synth_predictor_float_within_730_days_maximum_fallback_nan</th>\n",
- " <th>pred_synth_predictor_float_within_730_days_mean_fallback_nan</th>\n",
- " </tr>\n",
- " </thead>\n",
- " <tbody>\n",
- " <tr>\n",
- " <th>0</th>\n",
- " <td>9903</td>\n",
- " <td>1968-05-09 21:24:00</td>\n",
- " <td>9903-1968-05-09-21-24-00</td>\n",
- " <td>0.154981</td>\n",
- " <td>0.154981</td>\n",
- " <td>2.194319</td>\n",
- " <td>0.990763</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>1</th>\n",
- " <td>6447</td>\n",
- " <td>1967-09-25 18:08:00</td>\n",
- " <td>6447-1967-09-25-18-08-00</td>\n",
- " <td>8.930256</td>\n",
- " <td>5.396017</td>\n",
- " <td>9.774050</td>\n",
- " <td>5.582745</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>2</th>\n",
- " <td>4927</td>\n",
- " <td>1968-06-30 12:13:00</td>\n",
- " <td>4927-1968-06-30-12-13-00</td>\n",
- " <td>6.730694</td>\n",
- " <td>4.957251</td>\n",
- " <td>6.730694</td>\n",
- " <td>4.957251</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>3</th>\n",
- " <td>5475</td>\n",
- " <td>1967-01-09 03:09:00</td>\n",
- " <td>5475-1967-01-09-03-09-00</td>\n",
- " <td>9.497229</td>\n",
- " <td>6.081539</td>\n",
- " <td>9.497229</td>\n",
- " <td>5.999336</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>4</th>\n",
- " <td>3157</td>\n",
- " <td>1969-10-07 05:01:00</td>\n",
- " <td>3157-1969-10-07-05-01-00</td>\n",
- " <td>5.243176</td>\n",
- " <td>5.068323</td>\n",
- " <td>5.243176</td>\n",
- " <td>5.068323</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>...</th>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " <td>...</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>5957</th>\n",
- " <td>4228</td>\n",
- " <td>1967-02-26 05:45:00</td>\n",
- " <td>4228-1967-02-26-05-45-00</td>\n",
- " <td>6.844010</td>\n",
- " <td>4.353579</td>\n",
- " <td>6.844010</td>\n",
- " <td>3.792014</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>5958</th>\n",
- " <td>9745</td>\n",
- " <td>1969-02-04 01:18:00</td>\n",
- " <td>9745-1969-02-04-01-18-00</td>\n",
- " <td>3.858509</td>\n",
- " <td>3.858509</td>\n",
- " <td>3.858509</td>\n",
- " <td>2.394074</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>5959</th>\n",
- " <td>3385</td>\n",
- " <td>1967-07-17 19:18:00</td>\n",
- " <td>3385-1967-07-17-19-18-00</td>\n",
- " <td>9.370554</td>\n",
- " <td>5.463267</td>\n",
- " <td>9.370554</td>\n",
- " <td>5.769484</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>5960</th>\n",
- " <td>1421</td>\n",
- " <td>1968-04-15 15:53:00</td>\n",
- " <td>1421-1968-04-15-15-53-00</td>\n",
- " <td>8.972364</td>\n",
- " <td>8.972364</td>\n",
- " <td>8.972364</td>\n",
- " <td>7.732447</td>\n",
- " </tr>\n",
- " <tr>\n",
- " <th>5961</th>\n",
- " <td>1940</td>\n",
- " <td>1968-05-17 10:49:00</td>\n",
- " <td>1940-1968-05-17-10-49-00</td>\n",
- " <td>NaN</td>\n",
- " <td>NaN</td>\n",
- " <td>7.448374</td>\n",
- " <td>4.846514</td>\n",
- " </tr>\n",
- " </tbody>\n",
- "</table>\n",
- "<p>5962 rows × 7 columns</p>\n",
- "</div>"
- ],
- "text/plain": [
- " dw_ek_borger timestamp prediction_time_uuid \\\n",
- "0 9903 1968-05-09 21:24:00 9903-1968-05-09-21-24-00 \n",
- "1 6447 1967-09-25 18:08:00 6447-1967-09-25-18-08-00 \n",
- "2 4927 1968-06-30 12:13:00 4927-1968-06-30-12-13-00 \n",
- "3 5475 1967-01-09 03:09:00 5475-1967-01-09-03-09-00 \n",
- "4 3157 1969-10-07 05:01:00 3157-1969-10-07-05-01-00 \n",
- "... ... ... ... \n",
- "5957 4228 1967-02-26 05:45:00 4228-1967-02-26-05-45-00 \n",
- "5958 9745 1969-02-04 01:18:00 9745-1969-02-04-01-18-00 \n",
- "5959 3385 1967-07-17 19:18:00 3385-1967-07-17-19-18-00 \n",
- "5960 1421 1968-04-15 15:53:00 1421-1968-04-15-15-53-00 \n",
- "5961 1940 1968-05-17 10:49:00 1940-1968-05-17-10-49-00 \n",
- "\n",
- " pred_synth_predictor_float_within_365_days_maximum_fallback_nan \\\n",
- "0 0.154981 \n",
- "1 8.930256 \n",
- "2 6.730694 \n",
- "3 9.497229 \n",
- "4 5.243176 \n",
- "... ... \n",
- "5957 6.844010 \n",
- "5958 3.858509 \n",
- "5959 9.370554 \n",
- "5960 8.972364 \n",
- "5961 NaN \n",
- "\n",
- " pred_synth_predictor_float_within_365_days_mean_fallback_nan \\\n",
- "0 0.154981 \n",
- "1 5.396017 \n",
- "2 4.957251 \n",
- "3 6.081539 \n",
- "4 5.068323 \n",
- "... ... \n",
- "5957 4.353579 \n",
- "5958 3.858509 \n",
- "5959 5.463267 \n",
- "5960 8.972364 \n",
- "5961 NaN \n",
- "\n",
- " pred_synth_predictor_float_within_730_days_maximum_fallback_nan \\\n",
- "0 2.194319 \n",
- "1 9.774050 \n",
- "2 6.730694 \n",
- "3 9.497229 \n",
- "4 5.243176 \n",
- "... ... \n",
- "5957 6.844010 \n",
- "5958 3.858509 \n",
- "5959 9.370554 \n",
- "5960 8.972364 \n",
- "5961 7.448374 \n",
- "\n",
- " pred_synth_predictor_float_within_730_days_mean_fallback_nan \n",
- "0 0.990763 \n",
- "1 5.582745 \n",
- "2 4.957251 \n",
- "3 5.999336 \n",
- "4 5.068323 \n",
- "... ... \n",
- "5957 3.792014 \n",
- "5958 2.394074 \n",
- "5959 5.769484 \n",
- "5960 7.732447 \n",
- "5961 4.846514 \n",
- "\n",
- "[5962 rows x 7 columns]"
- ]
- },
- "execution_count": 10,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "skim(df)\n",
- "df"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3.10.7 ('.venv': poetry)",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.10.7"
- },
- "orig_nbformat": 4,
- "vscode": {
- "interpreter": {
- "hash": "d2b49c0af2d95979144de75823f7cfbb268839811992fdd0cb17fc1bb54ce815"
- }
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
\ No newline at end of file
|
Aarhus-Psychiatry-Research__timeseriesflattener-62
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/timeseriesflattener/feature_spec_objects.py:TemporalSpec.__init__",
"src/timeseriesflattener/feature_spec_objects.py:PredictorSpec.get_cutoff_date",
"src/timeseriesflattener/feature_spec_objects.py:OutcomeSpec.get_cutoff_date"
],
"edited_modules": [
"src/timeseriesflattener/feature_spec_objects.py:TemporalSpec",
"src/timeseriesflattener/feature_spec_objects.py:PredictorSpec",
"src/timeseriesflattener/feature_spec_objects.py:OutcomeSpec"
]
},
"file": "src/timeseriesflattener/feature_spec_objects.py"
},
{
"changes": {
"added_entities": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._get_cutoff_date_from_spec",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._check_that_spec_df_timestamp_col_is_correctly_formatted"
],
"added_modules": null,
"edited_entities": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._add_back_prediction_times_without_value",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._resolve_multiple_values_within_interval_days",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._flatten_temporal_values_to_df",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._get_temporal_feature",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener._drop_pred_time_if_insufficient_look_distance",
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener.add_spec"
],
"edited_modules": [
"src/timeseriesflattener/flattened_dataset.py:TimeseriesFlattener"
]
},
"file": "src/timeseriesflattener/flattened_dataset.py"
}
] |
Aarhus-Psychiatry-Research/timeseriesflattener
|
734c38b5e8fda8c5643ad389c00a734aeab82900
|
fix: remove hardcoded timestamp names
|
diff --git a/src/timeseriesflattener/feature_spec_objects.py b/src/timeseriesflattener/feature_spec_objects.py
index b498393..a1726bf 100644
--- a/src/timeseriesflattener/feature_spec_objects.py
+++ b/src/timeseriesflattener/feature_spec_objects.py
@@ -232,9 +232,6 @@ class TemporalSpec(AnySpec):
id_col_name: str = "id"
# Col name for ids in the input dataframe.
- timestamp_col_name: str = "timestamp"
- # Col name for timestamps in the input dataframe.
-
loader_kwargs: Optional[dict] = None
# Optional keyword arguments for the data loader
@@ -255,25 +252,6 @@ class TemporalSpec(AnySpec):
super().__init__(**data)
- timestamp_col_type = self.values_df[self.timestamp_col_name].dtype # type: ignore
-
- if timestamp_col_type not in ("Timestamp", "datetime64[ns]"):
- # Convert column dtype to datetime64[ns] if it isn't already
- log.info(
- f"{self.feature_name}: Converting timestamp column to datetime64[ns]",
- )
-
- self.values_df[self.timestamp_col_name] = pd.to_datetime(
- self.values_df[self.timestamp_col_name],
- )
-
- min_timestamp = min(self.values_df[self.timestamp_col_name])
-
- if min_timestamp < pd.Timestamp("1971-01-01"):
- log.warning(
- f"{self.feature_name}: Minimum timestamp is {min_timestamp} - perhaps ints were coerced to timestamps?",
- )
-
self.resolve_multiple_fn = data["resolve_multiple_fn"]
# override fallback strings with objects
@@ -305,20 +283,6 @@ class PredictorSpec(TemporalSpec):
super().__init__(**data)
- def get_cutoff_date(self) -> pd.Timestamp:
- """Get the cutoff date from a spec.
-
- A cutoff date is the earliest date that a prediction time can get data from the values_df.
- We do not want to include those prediction times, as we might make incorrect inferences.
- For example, if a spec says to look 5 years into the future, but we only have one year of data,
- there will necessarily be fewer outcomes - without that reflecting reality. This means our model won't generalise.
-
- Returns:
- pd.Timestamp: A cutoff date.
- """
- min_val_date = self.values_df[self.timestamp_col_name].min() # type: ignore
- return min_val_date + pd.Timedelta(days=self.lookbehind_days)
-
class OutcomeSpec(TemporalSpec):
"""Specification for a single outcome, where the df has been resolved."""
@@ -360,21 +324,6 @@ class OutcomeSpec(TemporalSpec):
return len(self.values_df[col_name].unique()) <= 2 # type: ignore
- def get_cutoff_date(self) -> pd.Timestamp:
- """Get the cutoff date from a spec.
-
- A cutoff date is the earliest date that a prediction time can get data from the values_df.
- We do not want to include those prediction times, as we might make incorrect inferences.
- For example, if a spec says to look 5 years into the future, but we only have one year of data,
- there will necessarily be fewer outcomes - without that reflecting reality. This means our model won't generalise.
-
- Returns:
- pd.Timestamp: A cutoff date.
- """
- max_val_date = self.values_df[self.timestamp_col_name].max() # type: ignore
-
- return max_val_date - pd.Timedelta(days=self.lookahead_days)
-
class MinGroupSpec(BaseModel):
"""Minimum specification for a group of features, whether they're looking ahead or behind.
diff --git a/src/timeseriesflattener/flattened_dataset.py b/src/timeseriesflattener/flattened_dataset.py
index fa5dba2..9a1f786 100644
--- a/src/timeseriesflattener/flattened_dataset.py
+++ b/src/timeseriesflattener/flattened_dataset.py
@@ -46,6 +46,7 @@ class SpecCollection(PydanticBaseModel):
static_specs: list[AnySpec] = []
def __len__(self):
+ """Return number of specs in collection."""
return (
len(self.outcome_specs) + len(self.predictor_specs) + len(self.static_specs)
)
@@ -185,6 +186,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
df: DataFrame,
pred_times_with_uuid: DataFrame,
pred_time_uuid_colname: str,
+ pred_timestamp_col_name: str,
) -> DataFrame:
"""Ensure all prediction times are represented in the returned
@@ -194,6 +196,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
df (DataFrame): Dataframe with prediction times but without uuid.
pred_times_with_uuid (DataFrame): Dataframe with prediction times and uuid.
pred_time_uuid_colname (str): Name of uuid column in both df and pred_times_with_uuid.
+ pred_itmestamp_col_name (str): Name of timestamp column in df.
Returns:
DataFrame: A merged dataframe with all prediction times.
@@ -204,13 +207,14 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
how="left",
on=pred_time_uuid_colname,
suffixes=("", "_temp"),
- ).drop(["timestamp_pred"], axis=1)
+ ).drop([pred_timestamp_col_name], axis=1)
@staticmethod
def _resolve_multiple_values_within_interval_days(
resolve_multiple: Callable,
df: DataFrame,
pred_time_uuid_colname: str,
+ val_timestamp_col_name: str,
) -> DataFrame:
"""Apply the resolve_multiple function to prediction_times where there
@@ -227,14 +231,14 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
# Convert timestamp val to numeric that can be used for resolve_multiple functions
# Numeric value amounts to days passed since 1/1/1970
try:
- df["timestamp_val"] = (
- df["timestamp_val"] - dt.datetime(1970, 1, 1)
+ df[val_timestamp_col_name] = (
+ df[val_timestamp_col_name] - dt.datetime(1970, 1, 1)
).dt.total_seconds() / 86400
except TypeError:
log.info("All values are NaT, returning empty dataframe")
# Sort by timestamp_pred in case resolve_multiple needs dates
- df = df.sort_values(by="timestamp_val").groupby(pred_time_uuid_colname)
+ df = df.sort_values(by=val_timestamp_col_name).groupby(pred_time_uuid_colname)
if isinstance(resolve_multiple, str):
resolve_multiple = resolve_multiple_fns.get(resolve_multiple)
@@ -300,6 +304,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
output_spec: AnySpec,
id_col_name: str,
pred_time_uuid_col_name: str,
+ timestamp_col_name: str,
verbose: bool = False, # noqa
) -> DataFrame:
"""Create a dataframe with flattened values (either predictor or
@@ -317,6 +322,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
static method.
pred_time_uuid_col_name (str): Name of uuid column in
prediction_times_with_uuid_df. Required because this is a static method.
+ timestamp_col_name (str): Name of timestamp column in. Required because this is a static method.
verbose (bool, optional): Whether to print progress.
@@ -334,6 +340,9 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
validate="m:m",
).drop(id_col_name, axis=1)
+ timestamp_val_col_name = f"{timestamp_col_name}_val"
+ timestamp_pred_col_name = f"{timestamp_col_name}_pred"
+
# Drop prediction times without event times within interval days
if isinstance(output_spec, OutcomeSpec):
direction = "ahead"
@@ -346,8 +355,8 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
df,
direction=direction,
interval_days=output_spec.interval_days,
- timestamp_pred_colname="timestamp_pred",
- timestamp_value_colname="timestamp_val",
+ timestamp_pred_colname=timestamp_pred_col_name,
+ timestamp_value_colname=timestamp_val_col_name,
)
# Add back prediction times that don't have a value, and fill them with fallback
@@ -355,14 +364,16 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
df=df,
pred_times_with_uuid=prediction_times_with_uuid_df,
pred_time_uuid_colname=pred_time_uuid_col_name,
+ pred_timestamp_col_name=timestamp_pred_col_name,
).fillna(output_spec.fallback)
- df["timestamp_val"].replace({output_spec.fallback: pd.NaT}, inplace=True)
+ df[timestamp_val_col_name].replace({output_spec.fallback: pd.NaT}, inplace=True)
df = TimeseriesFlattener._resolve_multiple_values_within_interval_days(
resolve_multiple=output_spec.resolve_multiple_fn,
df=df,
pred_time_uuid_colname=pred_time_uuid_col_name,
+ val_timestamp_col_name=timestamp_val_col_name,
)
# If resolve_multiple generates empty values,
@@ -415,6 +426,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
id_col_name=self.id_col_name,
pred_time_uuid_col_name=self.pred_time_uuid_col_name,
output_spec=feature_spec,
+ timestamp_col_name=self.timestamp_col_name,
)
# Write df to cache if exists
@@ -614,6 +626,26 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
self._df = df
+ def _get_cutoff_date_from_spec(self, spec: TemporalSpec) -> pd.Timestamp:
+ """Get the cutoff date from a spec.
+
+ A cutoff date is the earliest date that a prediction time can get data from the values_df.
+ We do not want to include those prediction times, as we might make incorrect inferences.
+ For example, if a spec says to look 5 years into the future, but we only have one year of data,
+ there will necessarily be fewer outcomes - without that reflecting reality. This means our model won't generalise.
+
+ Returns:
+ pd.Timestamp: A cutoff date.
+ """
+
+ if isinstance(spec, PredictorSpec):
+ min_val_date = spec.values_df[self.timestamp_col_name].min() # type: ignore
+ return min_val_date + pd.Timedelta(days=spec.lookbehind_days)
+
+ if isinstance(spec, OutcomeSpec):
+ max_val_date = spec.values_df[self.timestamp_col_name].max() # type: ignore
+ return max_val_date - pd.Timedelta(days=spec.lookahead_days)
+
@print_df_dimensions_diff
def _drop_pred_time_if_insufficient_look_distance(self, df: pd.DataFrame):
"""Drop prediction times if there is insufficient look distance.
@@ -638,7 +670,7 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
cutoff_date_ahead = pd.Timestamp("2200-01-01")
for spec in spec_batch:
- spec_cutoff_date = spec.get_cutoff_date()
+ spec_cutoff_date = self._get_cutoff_date_from_spec(spec=spec)
if isinstance(spec, OutcomeSpec):
cutoff_date_ahead = min(cutoff_date_ahead, spec_cutoff_date)
@@ -692,6 +724,30 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
if col not in spec.values_df.columns: # type: ignore
raise ValueError(f"Missing required column: {col}")
+ def _check_that_spec_df_timestamp_col_is_correctly_formatted(
+ self,
+ spec: TemporalSpec,
+ ):
+ """Check that timestamp column is correctly formatted. Attempt to coerce if possible."""
+ timestamp_col_type = spec.values_df[self.timestamp_col_name].dtype # type: ignore
+
+ if timestamp_col_type not in ("Timestamp", "datetime64[ns]"):
+ # Convert column dtype to datetime64[ns] if it isn't already
+ log.info(
+ f"{spec.feature_name}: Converting timestamp column to datetime64[ns]",
+ )
+
+ spec.values_df[self.timestamp_col_name] = pd.to_datetime( # type: ignore
+ spec.values_df[self.timestamp_col_name], # type: ignore
+ )
+
+ min_timestamp = min(spec.values_df[self.timestamp_col_name]) # type: ignore
+
+ if min_timestamp < pd.Timestamp("1971-01-01"):
+ log.warning(
+ f"{spec.feature_name}: Minimum timestamp is {min_timestamp} - perhaps ints were coerced to timestamps?",
+ )
+
def add_spec(
self,
spec: Union[list[AnySpec], AnySpec],
@@ -720,6 +776,11 @@ class TimeseriesFlattener: # pylint: disable=too-many-instance-attributes
self._check_that_spec_df_has_required_columns(spec=spec_i)
+ if isinstance(spec_i, TemporalSpec):
+ self._check_that_spec_df_timestamp_col_is_correctly_formatted(
+ spec=spec_i,
+ )
+
if isinstance(spec_i, OutcomeSpec):
self.unprocessed_specs.outcome_specs.append(spec_i)
elif isinstance(spec_i, PredictorSpec):
|
AbhinavOmprakash__py-htminify-8
|
[
{
"changes": {
"added_entities": [
"htminify/htminify.py:_protect_text",
"htminify/htminify.py:_substitute_with_hex_value",
"htminify/htminify.py:_reintroduce_protected_text"
],
"added_modules": [
"htminify/htminify.py:_protect_text",
"htminify/htminify.py:_substitute_with_hex_value",
"htminify/htminify.py:_reintroduce_protected_text"
],
"edited_entities": [
"htminify/htminify.py:minify",
"htminify/htminify.py:_replace_space_inside_tag"
],
"edited_modules": [
"htminify/htminify.py:minify",
"htminify/htminify.py:_replace_space_inside_tag"
]
},
"file": "htminify/htminify.py"
}
] |
AbhinavOmprakash/py-htminify
|
cd30ff52a48f28233d17709f4f36f14c206532ff
|
code blocks don't render properly

|
diff --git a/README.rst b/README.rst
index e22cf54..b8994d7 100644
--- a/README.rst
+++ b/README.rst
@@ -7,7 +7,7 @@ ________
* Using a web framework, like django, flask, and pyramid? We got you covered.
* Or you're feeling adventurous and you're building your own wsgi app? We got you covered there too. This will work with any program that complies with the WSGI specification
-* Using an encoding that is not UTF-8? Just pass an argument, and we'll take it from there. 😉
+* Using an encoding that is not UTF-8? Just pass an argument,and we'll take it from there. 😉
* Mixing Javascript and html? We'll try to minify that too, without judging you too much. (No promises though😜).
* No external dependencies.
@@ -72,7 +72,7 @@ An example flask file would be like this.
Note that we are wrapping the ``app.wsgi_app`` object and not the ``app`` object.
-**For any other WSGI app.**
+**For any other wsgi framework**
A similar procedure can be followed to integrate the middleware with other wsgi-Python web frameworks.
diff --git a/htminify/htminify.py b/htminify/htminify.py
index b7d10c4..2cfda2a 100644
--- a/htminify/htminify.py
+++ b/htminify/htminify.py
@@ -1,38 +1,69 @@
import re
+import uuid
-def minify(html: str) -> str:
- """A function that strips extra white space in an HTML string"""
+def minify(html: str) -> str:
+ """A function that strips extra white space in an HTML string."""
+ # protect tags like code|pre|textarea that are sensitive to whitespace
+ # strip off whitespace
+ # reintroduce the protected groups
+ html = _protect_text(html)
+
for (expression, replacement) in patterns:
html = re.sub(expression, replacement, html, flags=re.IGNORECASE)
+
+ html = _reintroduce_protected_text(html)
+
+ return html
+
+
+protected = {} # used to store the protected tags
+
+def _protect_text(html):
+ pre_text = re.findall(r"<pre>[\s\S]*?</pre>", html, re.IGNORECASE)
+ code_text = re.findall(r"<code>[\s\S]*?</code>", html, re.IGNORECASE)
+ text_area = re.findall(r"<textarea>[\s\S]*?</textarea>", html, re.IGNORECASE)
+
+ for text_matches in [pre_text, code_text, text_area]:
+ for match in text_matches:
+ html = _substitute_with_hex_value(match, html)
+
+ return html
+
+def _substitute_with_hex_value(text_match, html):
+ hex_id = uuid.uuid4().hex
+ html = re.sub(re.escape(text_match), hex_id, html)
+ protected[hex_id]=text_match
+ return html
+
+def _reintroduce_protected_text(html):
+ for hex_id, protected_str in protected.items():
+ html = re.sub(re.escape(hex_id), protected_str, html)
return html
def _replace_space_inside_tag(match):
# for replacing extra space characters In matched text
- return re.sub(r"(\s\s+)", " ", match.group(0))
-
+ return re.sub(r"\s\s+", " ", match.group(0))
patterns = [
# Space characters refer to all characters denoted by r"\s"
# for e.g tab, space, new line
(
- r"(?<=<)[\s\S]*?(?=>)", # For matching all text inside an HTML tag
+ r"(?<=<)[\s\S]*?(?=>)", #For matching all text inside an HTML tag < this text will be matched >
_replace_space_inside_tag,
),
- ( # this will prevent matching code inside <code|pre> tags nested inside <p> tags
- r"<\b(?!(code|pre|textarea)\b)\w+>[\s\S]*?<", # For matching text between tags
- _replace_space_inside_tag, # like <p> asdfawdf</p> but not Inside<code> </code>
+ (
+ r"(?<=>)[\s\S]*?(?=<)", # For matching text between tags
+ _replace_space_inside_tag, # like <p> asdfawdf</p>
),
(
- r"</\w+>[\s\S]*?<", # For matching text between tags
- _replace_space_inside_tag, # like <p> asdfawdf<p> but not Inside<code> </code>
+ r"/>[\s\S]*?<", # for matching text in between <img/> text <tag>
+ _replace_space_inside_tag
),
(r"(?<=>)\s*(?=<)", ""), # For matching space characters between HTML tags
(r"<!--*(.*?)--*>", ""), # for matching comments
- # The below two patterns are sensitive to ordering and must be at the end.
- (r"\s(?=<)",""), #For stripping Whitespace at the end of tags for e.g <p>word </p> -> <p>word</p>
- (r"(?<=>)\s",""),#For stripping Whitespace at the Beginning of tags for e.g <p> word</p> -> <p>word</p>
-]
+ (r"^[\s]*(?=<)", ""), #stripping whitespace at the beginning of the file
+]
\ No newline at end of file
diff --git a/pyproject.toml b/pyproject.toml
index 9cc0e20..1608c87 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,13 +1,16 @@
[tool.poetry]
name = "htminify"
-version = "0.1.0"
+version = "0.1.2"
description = "A lightweight html minifier for all Python web frameworks and WSGI apps."
authors = ["Abhinav Omprakash"]
-licence="BSD-3"
+license="BSD-3-Clause"
readme="README.rst"
homepage="https://github.com/AbhinavOmprakash/py-htminify"
repository="https://github.com/AbhinavOmprakash/py-htminify"
keywords=["html", "django","flask","wsgi", "middleware"]
+include=[
+ "LICENSE",
+]
[tool.poetry.dependencies]
python = "^3.6"
|
Abjad__abjad-ext-nauert-24
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"abjadext/nauert/gracehandlers.py:ConcatenatingGraceHandler.__init__"
],
"edited_modules": [
"abjadext/nauert/gracehandlers.py:ConcatenatingGraceHandler"
]
},
"file": "abjadext/nauert/gracehandlers.py"
}
] |
Abjad/abjad-ext-nauert
|
520f389f06e21ee0a094016b4f1e2b0cb58263c1
|
Check gracehandlers behaviors
There seem to be some odd behaviors in handling grace notes.
The first odd behavior results in a "grace rest" attaching to a pitched note, as shown below:
```
import abjad
from abjadext import nauert
quantizer = nauert.Quantizer()
durations = [1000, 1, 999]
pitches = [0, None, 0]
q_event_sequence = nauert.QEventSequence.from_millisecond_pitch_pairs(
tuple(zip(durations, pitches))
)
result = quantizer(q_event_sequence)
print(abjad.lilypond(result))
```
which results in
```
\new Voice
{
{
\tempo 4=60
%%% \time 4/4 %%%
c'4
\grace {
r16
}
c'4
r4
r4
}
}
```
The second one results in a grace note attaching to a rest.
A snippet might be uploaded later (or not).
|
diff --git a/abjadext/nauert/gracehandlers.py b/abjadext/nauert/gracehandlers.py
index 8813e0f..a2dbdd3 100644
--- a/abjadext/nauert/gracehandlers.py
+++ b/abjadext/nauert/gracehandlers.py
@@ -199,8 +199,8 @@ class ConcatenatingGraceHandler(GraceHandler):
.. container:: example
- When ``replace_rest_with_final_grace_note`` is set to ``False`` (the
- default behaviour), grace notes are allowed to be attached to a rest.
+ When ``replace_rest_with_final_grace_note`` is set to ``False``, grace
+ notes are allowed to be attached to a rest.
>>> quantizer = nauert.Quantizer()
>>> durations = [1000, 1, 999, 1000]
@@ -208,7 +208,9 @@ class ConcatenatingGraceHandler(GraceHandler):
>>> q_event_sequence = nauert.QEventSequence.from_millisecond_pitch_pairs(
... tuple(zip(durations, pitches))
... )
- >>> grace_handler = nauert.ConcatenatingGraceHandler()
+ >>> grace_handler = nauert.ConcatenatingGraceHandler(
+ ... replace_rest_with_final_grace_note=False
+ ... )
>>> result = quantizer(q_event_sequence, grace_handler=grace_handler)
>>> abjad.show(result) # doctest: +SKIP
@@ -233,13 +235,11 @@ class ConcatenatingGraceHandler(GraceHandler):
.. container:: example
- When ``replace_rest_with_final_grace_note`` is set to ``True``, any
- rest with grace notes attached to it is replaced by the last pitched
- grace note in the grace container.
+ When ``replace_rest_with_final_grace_note`` is set to ``True`` (the
+ default behavior), any rest with grace notes attached to it is replaced
+ by the last pitched grace note in the grace container.
- >>> grace_handler = nauert.ConcatenatingGraceHandler(
- ... replace_rest_with_final_grace_note=True
- ... )
+ >>> grace_handler = nauert.ConcatenatingGraceHandler()
>>> result = quantizer(q_event_sequence, grace_handler=grace_handler)
>>> abjad.show(result) # doctest: +SKIP
@@ -274,7 +274,7 @@ class ConcatenatingGraceHandler(GraceHandler):
self,
discard_grace_rest=True,
grace_duration=None,
- replace_rest_with_final_grace_note=False,
+ replace_rest_with_final_grace_note=True,
):
self._discard_grace_rest = discard_grace_rest
if grace_duration is None:
|
ActivisionGameScience__assertpy-55
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "assertpy/__init__.py"
},
{
"changes": {
"added_entities": [
"assertpy/assertpy.py:soft_assertions",
"assertpy/assertpy.py:assert_warn"
],
"added_modules": [
"assertpy/assertpy.py:soft_assertions",
"assertpy/assertpy.py:assert_warn"
],
"edited_entities": [
"assertpy/assertpy.py:assert_soft",
"assertpy/assertpy.py:assert_that",
"assertpy/assertpy.py:AssertionBuilder.__init__",
"assertpy/assertpy.py:AssertionBuilder.extracting",
"assertpy/assertpy.py:AssertionBuilder.raises",
"assertpy/assertpy.py:AssertionBuilder.when_called_with",
"assertpy/assertpy.py:AssertionBuilder._err"
],
"edited_modules": [
"assertpy/assertpy.py:assert_soft",
"assertpy/assertpy.py:assert_that",
"assertpy/assertpy.py:AssertionBuilder"
]
},
"file": "assertpy/assertpy.py"
}
] |
ActivisionGameScience/assertpy
|
ed43bee91eadd55f6cc9004e6f3862a97e0d2190
|
correct implementation of soft assertions
Hi!
This is not a bug report, but more like a discussion kick-starter regarding soft assertions. And if we happen to agree on a different implementation, I'll be more than happy to create a PR.
What I suggest is soft assertions to be implemented as in other languages libraries. E.g [soft assertions in AssertJ](http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#soft-assertions).
Soft assertions usually have a special value in higher levels of testing than unit, e.g. integration or system tests, when the result feedback is not as fast as with unit test.
So basically a test is more "expensive" to run in terms of resources like CPU, memory, and specially time. And we want to take the most value out of each execution.
Let's assume that I have a test that:
- Logs in
- Creates a new user in the system with default settings
- And verifies that the user has a
* default locale = X
* default timezone = Y
* default privileges = Z
* etc, etc
If any of these are missing or wrong, I want the test to fail. However, with regular assertions if the locale is missing the test will fail as expected but I won't have any information whether the system meets the other requirements.
As you know, that's when soft assertions come handy. The problem I see though, is that in your implementation, you silently pass, I mean.. you print a warning in stdout, but the test will pass. And that's a wrong approach IMO, as it requires human intervention (someone reading the screen), so those assertions won't have any effect if tests are run, for instance, in jenkins as part of CI/CD pipeline.
What I suggest is what AssertJ does. You run assertions in a group, so even if the "locale" assertion fails, you still run the "timezone" and the "privileges" assertions. After all the assertions have been executed an AssertionError is raised if at least one assertion in the group failed. The error will contain the details of all those assertions in the group that failed.
Does all this make sense to you? WDYT?
Regards!
|
diff --git a/README.md b/README.md
index 91b1eb5..99edf06 100644
--- a/README.md
+++ b/README.md
@@ -282,7 +282,7 @@ Fluent assertions against the value of a given key can be done by prepending `ha
```py
fred = {'first_name': 'Fred', 'last_name': 'Smith', 'shoe_size': 12}
-
+
assert_that(fred).has_first_name('Fred')
assert_that(fred).has_last_name('Smith')
assert_that(fred).has_shoe_size(12)
@@ -534,7 +534,7 @@ As noted above, dynamic assertions also work on dicts:
```py
fred = {'first_name': 'Fred', 'last_name': 'Smith'}
-
+
assert_that(fred).has_first_name('Fred')
assert_that(fred).has_last_name('Smith')
```
@@ -613,24 +613,24 @@ Expected <3> to be equal to <2>, but was not.
The `described_as()` helper causes the custom message `adding stuff` to be prepended to the front of the second error.
-#### Soft Assertions
+#### Just A Warning
-There are times when you don't want to a test to fail at all, instead you only want a warning message. In this case, just replace `assert_that` with `assert_soft`.
+There are times when you only want a warning message instead of an failing test. In this case, just replace `assert_that` with `assert_warn`.
```py
-assert_soft('foo').is_length(4)
-assert_soft('foo').is_empty()
-assert_soft('foo').is_false()
-assert_soft('foo').is_digit()
-assert_soft('123').is_alpha()
-assert_soft('foo').is_upper()
-assert_soft('FOO').is_lower()
-assert_soft('foo').is_equal_to('bar')
-assert_soft('foo').is_not_equal_to('foo')
-assert_soft('foo').is_equal_to_ignoring_case('BAR')
+assert_warn('foo').is_length(4)
+assert_warn('foo').is_empty()
+assert_warn('foo').is_false()
+assert_warn('foo').is_digit()
+assert_warn('123').is_alpha()
+assert_warn('foo').is_upper()
+assert_warn('FOO').is_lower()
+assert_warn('foo').is_equal_to('bar')
+assert_warn('foo').is_not_equal_to('foo')
+assert_warn('foo').is_equal_to_ignoring_case('BAR')
```
-The above soft assertions print the following warning messages (but an `AssertionError` is never raised):
+The above assertions just print the following warning messages, and an `AssertionError` is never raised:
```
Expected <foo> to be of length <4>, but was <3>.
diff --git a/assertpy/__init__.py b/assertpy/__init__.py
index 385ab52..f673973 100644
--- a/assertpy/__init__.py
+++ b/assertpy/__init__.py
@@ -1,2 +1,2 @@
from __future__ import absolute_import
-from .assertpy import assert_that, assert_soft, contents_of, fail, __version__
+from .assertpy import assert_that, assert_warn, soft_assertions, contents_of, fail, __version__
diff --git a/assertpy/assertpy.py b/assertpy/assertpy.py
index 462eee4..a1a644d 100644
--- a/assertpy/assertpy.py
+++ b/assertpy/assertpy.py
@@ -36,6 +36,7 @@ import datetime
import numbers
import collections
import inspect
+from contextlib import contextmanager
__version__ = '0.9'
@@ -48,14 +49,43 @@ else:
xrange = xrange
unicode = unicode
+
+### soft assertions ###
+_soft_ctx = False
+_soft_err = []
+
+@contextmanager
+def soft_assertions():
+ global _soft_ctx
+ global _soft_err
+
+ _soft_ctx = True
+ _soft_err = []
+
+ yield
+
+ if _soft_err:
+ out = 'soft assertion failures:'
+ for i,msg in enumerate(_soft_err):
+ out += '\n%d. %s' % (i+1, msg)
+ raise AssertionError(out)
+
+ _soft_err = []
+ _soft_ctx = False
+
+
+### factory methods ###
def assert_that(val, description=''):
"""Factory method for the assertion builder with value to be tested and optional description."""
+ global _soft_ctx
+ if _soft_ctx:
+ return AssertionBuilder(val, description, 'soft')
return AssertionBuilder(val, description)
-def assert_soft(val, description=''):
+def assert_warn(val, description=''):
"""Factory method for the assertion builder with value to be tested, optional description, and
- just print assertion failures, don't raise exceptions."""
- return AssertionBuilder(val, description, True)
+ just warn on assertion failures instead of raisings exceptions."""
+ return AssertionBuilder(val, description, 'warn')
def contents_of(f, encoding='utf-8'):
"""Helper to read the contents of the given file or path into a string with the given encoding.
@@ -96,14 +126,15 @@ def fail(msg=''):
else:
raise AssertionError('Fail: %s!' % msg)
+
class AssertionBuilder(object):
"""Assertion builder."""
- def __init__(self, val, description, soft=False, expected=None):
+ def __init__(self, val, description='', kind=None, expected=None):
"""Construct the assertion builder."""
self.val = val
self.description = description
- self.soft = soft
+ self.kind = kind
self.expected = expected
def described_as(self, description):
@@ -833,7 +864,7 @@ class AssertionBuilder(object):
else:
raise ValueError('val does not have property or zero-arg method <%s>' % name)
extracted.append(tuple(items) if len(items) > 1 else items[0])
- return AssertionBuilder(extracted, self.description)
+ return AssertionBuilder(extracted, self.description, self.kind)
### dynamic assertions ###
def __getattr__(self, attr):
@@ -878,7 +909,7 @@ class AssertionBuilder(object):
raise TypeError('val must be function')
if not issubclass(ex, BaseException):
raise TypeError('given arg must be exception')
- return AssertionBuilder(self.val, self.description, expected=ex)
+ return AssertionBuilder(self.val, self.description, self.kind, ex)
def when_called_with(self, *some_args, **some_kwargs):
"""Asserts the val function when invoked with the given args and kwargs raises the expected exception."""
@@ -889,7 +920,7 @@ class AssertionBuilder(object):
except BaseException as e:
if issubclass(type(e), self.expected):
# chain on with exception message as val
- return AssertionBuilder(str(e), self.description)
+ return AssertionBuilder(str(e), self.description, self.kind)
else:
# got exception, but wrong type, so raise
self._err('Expected <%s> to raise <%s> when called with (%s), but raised <%s>.' % (
@@ -908,9 +939,13 @@ class AssertionBuilder(object):
def _err(self, msg):
"""Helper to raise an AssertionError, and optionally prepend custom description."""
out = '%s%s' % ('[%s] ' % self.description if len(self.description) > 0 else '', msg)
- if self.soft:
+ if self.kind == 'warn':
print(out)
return self
+ elif self.kind == 'soft':
+ global _soft_err
+ _soft_err.append(out)
+ return self
else:
raise AssertionError(out)
|
Adyen__adyen-python-api-library-276
|
[
{
"changes": {
"added_entities": [
"Adyen/client.py:AdyenClient._raise_http_error"
],
"added_modules": null,
"edited_entities": [
"Adyen/client.py:AdyenClient._set_url_version",
"Adyen/client.py:AdyenClient._handle_response",
"Adyen/client.py:AdyenClient._handle_http_error"
],
"edited_modules": [
"Adyen/client.py:AdyenClient"
]
},
"file": "Adyen/client.py"
}
] |
Adyen/adyen-python-api-library
|
72bd79756c6fe5de567e7ca0e61b27d304d7e8c0
|
`TerminalsTerminalLevelApi.reassign_terminal` throws JSONDecodeError
**Describe the bug**
All calls to `TerminalsTerminalLevelApi.reassign_terminal` throw a JSONDecodeError
**To Reproduce**
```python
from Adyen import AdyenClient
from Adyen.services.management import TerminalsTerminalLevelApi
API_KEY = '<redacted>'
STORE_ID = 'ST3224Z223225T5JQTRDD7CRZ'
TERMINAL_ID = 'AMS1-000168223606144'
client = AdyenClient(xapikey=API_KEY)
api = TerminalsTerminalLevelApi(client=client)
api.reassign_terminal({
'storeId': STORE_ID,
'inventory': False,
}, TERMINAL_ID)
```
Output:
```
Traceback (most recent call last):
File "/Users/luhn/Code/revenue/sandbox/adyentest.py", line 12, in <module>
api.reassign_terminal({
File "/Users/luhn/.pyenv/versions/revenue/lib/python3.10/site-packages/Adyen/services/management/terminals_terminal_level_api.py", line 30, in reassign_terminal
return self.client.call_adyen_api(request, self.service, method, endpoint, idempotency_key, **kwargs)
File "/Users/luhn/.pyenv/versions/revenue/lib/python3.10/site-packages/Adyen/client.py", line 369, in call_adyen_api
adyen_result = self._handle_response(url, raw_response, raw_request,
File "/Users/luhn/.pyenv/versions/revenue/lib/python3.10/site-packages/Adyen/client.py", line 435, in _handle_response
response = json_lib.loads(raw_response)
File "/Users/luhn/.pyenv/versions/3.10.1/lib/python3.10/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/Users/luhn/.pyenv/versions/3.10.1/lib/python3.10/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/luhn/.pyenv/versions/3.10.1/lib/python3.10/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
```
**Expected behavior**
No exception should be thrown.
**Screenshots**
N/A
**Desktop (please complete the following information):**
- OS: Mac OS, Python 3.10
- Browser: N/A
- Version: 10.0.0
**Additional context**
According to [the docs](https://docs.adyen.com/api-explorer/Management/3/post/terminals/_terminalId_/reassign), reassigning a terminal returns HTTP 200 with no content. My own testing confirms this:
```
curl -i https://management-test.adyen.com/v3/terminals/AMS1-000168223606144/reassign -d '{"storeId": "ST3224Z223225T5JQTRDD7CRZ", "inventory": false}' -H 'Content-Type: application/json' -H 'x-API-key: <redacted>'
HTTP/1.1 200
traceparent: 00-36fb314f5ca8069a20974823e9986efd-9f224b0d4601a27c-01
Set-Cookie: <redacted>
pspReference: GVTHZQPNN8JSTC82
requestid: GVTHZQPNN8JSTC82
Content-Type: application/json;charset=utf-8
Transfer-Encoding: chunked
Date: Mon, 13 Nov 2023 23:45:44 GMT
```
The SDK expects the body to be valid JSON, except for HTTP 204.
https://github.com/Adyen/adyen-python-api-library/blob/d6253f98202f4ef136d9859895e75a4c599bb1af/Adyen/client.py#L434-L437
Personally I think the SDK is right and the API is wrong—Especially since the API declares the response is JSON (`Content-Type: application/json;charset=utf-8`) yet does not return valid JSON.
|
diff --git a/Adyen/__init__.py b/Adyen/__init__.py
index 712155e..3e9a8a8 100644
--- a/Adyen/__init__.py
+++ b/Adyen/__init__.py
@@ -1,5 +1,3 @@
-#!/bin/python
-
from __future__ import absolute_import, division, unicode_literals
from . import util
diff --git a/Adyen/client.py b/Adyen/client.py
index cd45b98..2e40e97 100644
--- a/Adyen/client.py
+++ b/Adyen/client.py
@@ -1,5 +1,3 @@
-#!/bin/python
-
from __future__ import absolute_import, division, unicode_literals
import json as json_lib
@@ -266,18 +264,18 @@ class AdyenClient(object):
def _set_url_version(self, service, endpoint):
version_lookup = {"binlookup": self.api_bin_lookup_version,
- "checkout": self.api_checkout_version,
- "management": self.api_management_version,
- "payments": self.api_payment_version,
- "payouts": self.api_payout_version,
- "recurring": self.api_recurring_version,
- "terminal": self.api_terminal_version,
- "legalEntityManagement": self.api_legal_entity_management_version,
- "dataProtection": self.api_data_protection_version,
- "transfers": self.api_transfers_version,
- "storedValue": self.api_stored_value_version,
- "balancePlatform": self.api_balance_platform_version,
- "disputes": self.api_disputes_version
+ "checkout": self.api_checkout_version,
+ "management": self.api_management_version,
+ "payments": self.api_payment_version,
+ "payouts": self.api_payout_version,
+ "recurring": self.api_recurring_version,
+ "terminal": self.api_terminal_version,
+ "legalEntityManagement": self.api_legal_entity_management_version,
+ "dataProtection": self.api_data_protection_version,
+ "transfers": self.api_transfers_version,
+ "storedValue": self.api_stored_value_version,
+ "balancePlatform": self.api_balance_platform_version,
+ "disputes": self.api_disputes_version
}
new_version = f"v{version_lookup[service]}"
@@ -383,7 +381,7 @@ class AdyenClient(object):
def _handle_response(self, url, raw_response, raw_request,
status_code, headers):
"""This parses the content from raw communication, raising an error if
- anything other than 200 was returned.
+ anything other than 2xx was returned.
Args:
url (str): URL where request was made
@@ -391,58 +389,31 @@ class AdyenClient(object):
raw_request (str): The raw response returned by Adyen
status_code (int): The HTTP status code
headers (dict): Key/Value of the headers.
- request_dict (dict): The original request dictionary that was given
- to the HTTPClient.
Returns:
AdyenResult: Result object if successful.
"""
- if status_code not in [200, 201, 204]:
+ try:
+ response = json_lib.loads(raw_response)
+ except json_lib.JSONDecodeError:
response = {}
- # If the result can't be parsed into json, most likely is raw html.
- # Some response are neither json or raw html, handle them here:
- if raw_response:
- response = json_lib.loads(raw_response)
- # Pass raised error to error handler.
- self._handle_http_error(url, response, status_code,
- headers.get('pspReference'),
- raw_request, raw_response,
- headers)
-
- try:
- if response['errorCode']:
- raise AdyenAPICommunicationError(
- "Unexpected error while communicating with Adyen."
- " Received the response data:'{}', HTTP Code:'{}'. "
- "Please reach out to support@adyen.com if the "
- "problem persists with the psp:{}".format(
- raw_response,
- status_code,
- headers.get('pspReference')),
- status_code=status_code,
- raw_request=raw_request,
- raw_response=raw_response,
- url=url,
- psp=headers.get('pspReference'),
- headers=headers,
- error_code=response['errorCode'])
- except KeyError:
- erstr = 'KeyError: errorCode'
- raise AdyenAPICommunicationError(erstr)
+
+ if status_code not in [200, 201, 202, 204]:
+ self._raise_http_error(url, response, status_code,
+ headers.get('pspReference'),
+ raw_request, raw_response,
+ headers)
else:
- if status_code != 204:
- response = json_lib.loads(raw_response)
- else:
- response = {}
psp = self._get_psp(response, headers)
return AdyenResult(message=response, status_code=status_code,
psp=psp, raw_request=raw_request,
raw_response=raw_response)
- def _handle_http_error(self, url, response_obj, status_code, psp_ref,
- raw_request, raw_response, headers):
- """This function handles the non 200 responses from Adyen, raising an
+ @staticmethod
+ def _raise_http_error(url, response_obj, status_code, psp_ref,
+ raw_request, raw_response, headers):
+ """This function handles the non 2xx responses from Adyen, raising an
error that should provide more information.
Args:
@@ -456,7 +427,7 @@ class AdyenClient(object):
headers(dict): headers of the response
Returns:
- None
+ None: It never returns
"""
if response_obj == {}:
@@ -484,9 +455,9 @@ class AdyenClient(object):
elif status_code == 500:
raise AdyenAPICommunicationError(message, raw_request, raw_response, url, psp_ref, headers, status_code,
error_code)
- else:
- raise AdyenAPIResponseError(message, raw_request, raw_response, url, psp_ref, headers, status_code,
- error_code)
+
+ raise AdyenAPIResponseError(message, raw_request, raw_response, url, psp_ref, headers, status_code,
+ error_code)
@staticmethod
def _get_psp(response, headers):
diff --git a/Adyen/httpclient.py b/Adyen/httpclient.py
index 954aba5..4b8d310 100644
--- a/Adyen/httpclient.py
+++ b/Adyen/httpclient.py
@@ -1,5 +1,3 @@
-#!/bin/python
-
from __future__ import absolute_import, division, unicode_literals
try:
@@ -49,7 +47,6 @@ class HTTPClient(object):
self.timeout = timeout
-
def _pycurl_request(
self,
method,
|
AgentOps-AI__AgentStack-77
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "agentstack/cli/__init__.py"
},
{
"changes": {
"added_entities": [
"agentstack/cli/cli.py:configure_default_model"
],
"added_modules": [
"agentstack/cli/cli.py:configure_default_model"
],
"edited_entities": null,
"edited_modules": null
},
"file": "agentstack/cli/cli.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"agentstack/generation/agent_generation.py:generate_agent"
],
"edited_modules": [
"agentstack/generation/agent_generation.py:generate_agent"
]
},
"file": "agentstack/generation/agent_generation.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"agentstack/generation/files.py:ConfigFile"
]
},
"file": "agentstack/generation/files.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"agentstack/main.py:main"
],
"edited_modules": [
"agentstack/main.py:main"
]
},
"file": "agentstack/main.py"
}
] |
AgentOps-AI/AgentStack
|
c2725af63fefa393169f30be0689f2b4f3f0e4b3
|
Dynamically load model providers
In the agent wizard section of the CLI, it asks to enter the model and provider for the agent to use.
Any provider/model that works in LiteLLM should be accepted.
Import or create a list of all acceptable providers and associated models.
In the AgentWizard, ask the user to select the provider (show top 5 most common, then an other option that shows all).
After selecting the provider, ask them which model.
The associated provider/model should be stored in the agent datatype as a string with format `provider/model`
|
diff --git a/agentstack/cli/__init__.py b/agentstack/cli/__init__.py
index 3c35ec3..afd42af 100644
--- a/agentstack/cli/__init__.py
+++ b/agentstack/cli/__init__.py
@@ -1,1 +1,1 @@
-from .cli import init_project_builder, list_tools
+from .cli import init_project_builder, list_tools, configure_default_model
diff --git a/agentstack/cli/cli.py b/agentstack/cli/cli.py
index 9b560d1..f10866b 100644
--- a/agentstack/cli/cli.py
+++ b/agentstack/cli/cli.py
@@ -16,10 +16,18 @@ from cookiecutter.main import cookiecutter
from .agentstack_data import FrameworkData, ProjectMetadata, ProjectStructure, CookiecutterData
from agentstack.logger import log
from agentstack.utils import get_package_path
+from agentstack.generation.files import ConfigFile
from agentstack.generation.tool_generation import get_all_tools
from .. import generation
from ..utils import open_json_file, term_color, is_snake_case
+PREFERRED_MODELS = [
+ 'openai/gpt-4o',
+ 'anthropic/claude-3-5-sonnet',
+ 'openai/o1-preview',
+ 'openai/gpt-4-turbo',
+ 'anthropic/claude-3-opus',
+]
def init_project_builder(slug_name: Optional[str] = None, template: Optional[str] = None, use_wizard: bool = False):
if slug_name and not is_snake_case(slug_name):
@@ -114,6 +122,27 @@ def welcome_message():
print(border)
+def configure_default_model(path: Optional[str] = None):
+ """Set the default model"""
+ agentstack_config = ConfigFile(path)
+ if agentstack_config.default_model:
+ return # Default model already set
+
+ print("Project does not have a default model configured.")
+ other_msg = f"Other (enter a model name)"
+ model = inquirer.list_input(
+ message="Which model would you like to use?",
+ choices=PREFERRED_MODELS + [other_msg],
+ )
+
+ if model == other_msg: # If the user selects "Other", prompt for a model name
+ print(f'A list of available models is available at: "https://docs.litellm.ai/docs/providers"')
+ model = inquirer.text(message="Enter the model name")
+
+ with ConfigFile(path) as agentstack_config:
+ agentstack_config.default_model = model
+
+
def ask_framework() -> str:
framework = "CrewAI"
# framework = inquirer.list_input(
diff --git a/agentstack/generation/agent_generation.py b/agentstack/generation/agent_generation.py
index f13a5d9..bf64dd2 100644
--- a/agentstack/generation/agent_generation.py
+++ b/agentstack/generation/agent_generation.py
@@ -2,6 +2,7 @@ from typing import Optional, List
from .gen_utils import insert_code_after_tag, get_crew_components, CrewComponent
from agentstack.utils import verify_agentstack_project, get_framework
+from agentstack.generation.files import ConfigFile
import os
from ruamel.yaml import YAML
from ruamel.yaml.scalarstring import FoldedScalarString
@@ -14,6 +15,7 @@ def generate_agent(
backstory: Optional[str],
llm: Optional[str]
):
+ agentstack_config = ConfigFile() # TODO path
if not role:
role = 'Add your role here'
if not goal:
@@ -21,7 +23,7 @@ def generate_agent(
if not backstory:
backstory = 'Add your backstory here'
if not llm:
- llm = 'openai/gpt-4o'
+ llm = agentstack_config.default_model
verify_agentstack_project()
@@ -37,9 +39,6 @@ def generate_agent(
print(f"Added agent \"{name}\" to your AgentStack project successfully!")
-
-
-
def generate_crew_agent(
name,
role: Optional[str] = 'Add your role here',
diff --git a/agentstack/generation/files.py b/agentstack/generation/files.py
index 0fc1fb1..b1c226c 100644
--- a/agentstack/generation/files.py
+++ b/agentstack/generation/files.py
@@ -31,10 +31,13 @@ class ConfigFile(BaseModel):
A list of tools that are currently installed in the project.
telemetry_opt_out: Optional[bool]
Whether the user has opted out of telemetry.
+ default_model: Optional[str]
+ The default model to use when generating agent configurations.
"""
framework: Optional[str] = DEFAULT_FRAMEWORK
tools: list[str] = []
telemetry_opt_out: Optional[bool] = None
+ default_model: Optional[str] = None
def __init__(self, path: Union[str, Path, None] = None):
path = Path(path) if path else Path.cwd()
diff --git a/agentstack/main.py b/agentstack/main.py
index 14a448c..77a7ed7 100644
--- a/agentstack/main.py
+++ b/agentstack/main.py
@@ -2,7 +2,7 @@ import argparse
import os
import sys
-from agentstack.cli import init_project_builder, list_tools
+from agentstack.cli import init_project_builder, list_tools, configure_default_model
from agentstack.telemetry import track_cli_command
from agentstack.utils import get_version, get_framework
import agentstack.generation as generation
@@ -102,6 +102,8 @@ def main():
os.system('python src/main.py')
elif args.command in ['generate', 'g']:
if args.generate_command in ['agent', 'a']:
+ if not args.llm:
+ configure_default_model()
generation.generate_agent(args.name, args.role, args.goal, args.backstory, args.llm)
elif args.generate_command in ['task', 't']:
generation.generate_task(args.name, args.description, args.expected_output, args.agent)
|
Akkudoktor-EOS__EOS-459
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/akkudoktoreos/utils/visualize.py:prepare_visualize"
],
"edited_modules": [
"src/akkudoktoreos/utils/visualize.py:prepare_visualize"
]
},
"file": "src/akkudoktoreos/utils/visualize.py"
}
] |
Akkudoktor-EOS/EOS
|
d912561bfbe5c1c97505f89225c3f9650b00c3c7
|
[BUG]: Exception in visualize
### Describe the issue:
optimize results in exception.
### Reproduceable code example:
```python
# report.create_line_chart_date(
# next_full_hour_date,
# [
# np.full(
# len(parameters.ems.gesamtlast) - start_hour,
# parameters.ems.einspeiseverguetung_euro_pro_wh,
# )
# ],
# title="Remuneration",
# # xlabel="Hours", # not enough space
# ylabel="€/Wh",
# x2label=None, # not enough space
# )
```
### Error message:
```shell
<details>
Feb 10 08:36:38 openhab fastapi[203759]: Time evaluate inner: 84.2737 sec.
Feb 10 08:36:38 openhab fastapi[203759]: INFO 192.168.71.12:34946 - "POST /optimize HTTP/1.1" 500
Feb 10 08:36:38 openhab fastapi[203759]: ERROR Exception in ASGI application
Feb 10 08:36:38 openhab fastapi[203759]: Traceback (most recent call last):
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 409, in run_asgi
Feb 10 08:36:38 openhab fastapi[203759]: result = await app( # type: ignore[func-returns-value]
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
Feb 10 08:36:38 openhab fastapi[203759]: return await self.app(scope, receive, send)
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/fastapi/applications.py", line 1054, in __call__
Feb 10 08:36:38 openhab fastapi[203759]: await super().__call__(scope, receive, send)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/applications.py", line 112, in __call__
Feb 10 08:36:38 openhab fastapi[203759]: await self.middleware_stack(scope, receive, send)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__
Feb 10 08:36:38 openhab fastapi[203759]: raise exc
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__
Feb 10 08:36:38 openhab fastapi[203759]: await self.app(scope, receive, _send)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__
Feb 10 08:36:38 openhab fastapi[203759]: await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
Feb 10 08:36:38 openhab fastapi[203759]: raise exc
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
Feb 10 08:36:38 openhab Node-RED[205792]: 10 Feb 08:36:38 - [warn] [http request:31d21009fe6e6f10] JSON-Parse-Fehler
Feb 10 08:36:38 openhab Node-RED[205792]: 10 Feb 08:36:38 - [error] [function:Store Solution] TypeError: Cannot read properties of undefined (reading 'Last_Wh_pro_Stunde')
Feb 10 08:36:38 openhab fastapi[203759]: await app(scope, receive, sender)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__
Feb 10 08:36:38 openhab fastapi[203759]: await self.middleware_stack(scope, receive, send)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/routing.py", line 735, in app
Feb 10 08:36:38 openhab fastapi[203759]: await route.handle(scope, receive, send)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle
Feb 10 08:36:38 openhab fastapi[203759]: await self.app(scope, receive, send)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/routing.py", line 76, in app
Feb 10 08:36:38 openhab fastapi[203759]: await wrap_app_handling_exceptions(app, request)(scope, receive, send)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
Feb 10 08:36:38 openhab fastapi[203759]: raise exc
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
Feb 10 08:36:38 openhab fastapi[203759]: await app(scope, receive, sender)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/routing.py", line 73, in app
Feb 10 08:36:38 openhab fastapi[203759]: response = await f(request)
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/fastapi/routing.py", line 301, in app
Feb 10 08:36:38 openhab fastapi[203759]: raw_response = await run_endpoint_function(
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/fastapi/routing.py", line 214, in run_endpoint_function
Feb 10 08:36:38 openhab fastapi[203759]: return await run_in_threadpool(dependant.call, **values)
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/starlette/concurrency.py", line 37, in run_in_threadpool
Feb 10 08:36:38 openhab fastapi[203759]: return await anyio.to_thread.run_sync(func)
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/anyio/to_thread.py", line 56, in run_sync
Feb 10 08:36:38 openhab fastapi[203759]: return await get_async_backend().run_sync_in_worker_thread(
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 2461, in run_sync_in_worker_thread
Feb 10 08:36:38 openhab fastapi[203759]: return await future
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 962, in run
Feb 10 08:36:38 openhab fastapi[203759]: result = context.run(func, *args)
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^^^^^^^^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/src/akkudoktoreos/server/eos.py", line 838, in fastapi_optimize
Feb 10 08:36:38 openhab fastapi[203759]: result = opt_class.optimierung_ems(parameters=parameters, start_hour=start_hour)
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/src/akkudoktoreos/optimization/genetic.py", line 670, in optimierung_ems
Feb 10 08:36:38 openhab fastapi[203759]: prepare_visualize(parameters, visualize, start_hour=start_hour)
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/src/akkudoktoreos/utils/visualize.py", line 455, in prepare_visualize
Feb 10 08:36:38 openhab fastapi[203759]: # np.full(
Feb 10 08:36:38 openhab fastapi[203759]: ^^^^^^^^^
Feb 10 08:36:38 openhab fastapi[203759]: File "/opt/EOS/.venv/lib/python3.11/site-packages/numpy/_core/numeric.py", line 353, in full
Feb 10 08:36:38 openhab fastapi[203759]: multiarray.copyto(a, fill_value, casting='unsafe')
Feb 10 08:36:38 openhab fastapi[203759]: ValueError: could not broadcast input array from shape (48,) into shape (40,)
</details>
```
### Version information:
master
|
diff --git a/src/akkudoktoreos/utils/visualize.py b/src/akkudoktoreos/utils/visualize.py
index fc684c9..51ccc63 100644
--- a/src/akkudoktoreos/utils/visualize.py
+++ b/src/akkudoktoreos/utils/visualize.py
@@ -454,7 +454,9 @@ def prepare_visualize(
[
np.full(
len(parameters.ems.gesamtlast) - start_hour,
- parameters.ems.einspeiseverguetung_euro_pro_wh,
+ parameters.ems.einspeiseverguetung_euro_pro_wh[start_hour:]
+ if isinstance(parameters.ems.einspeiseverguetung_euro_pro_wh, list)
+ else parameters.ems.einspeiseverguetung_euro_pro_wh,
)
],
title="Remuneration",
|
Alexei-Kornienko__schematics_to_swagger-7
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"schematics_to_swagger/__init__.py:model_to_definition"
],
"edited_modules": [
"schematics_to_swagger/__init__.py:model_to_definition"
]
},
"file": "schematics_to_swagger/__init__.py"
}
] |
Alexei-Kornienko/schematics_to_swagger
|
3ddc537a8ed7682e9bb709ebd749b99d7ef09473
|
Hide private model fields in swagger doc
|
diff --git a/schematics_to_swagger/__init__.py b/schematics_to_swagger/__init__.py
index d108f3f..d203de0 100644
--- a/schematics_to_swagger/__init__.py
+++ b/schematics_to_swagger/__init__.py
@@ -54,17 +54,24 @@ def _map_schematics_type(t):
def model_to_definition(model):
- fields = model.fields.items()
+ properties = {}
+ required = []
+
+ for field_name, field in model.fields.items():
+ if field_name.startswith(f'_{model.__name__}'):
+ continue # Exclude private fields
+ properties[field_name] = _map_schematics_type(field)
+ if getattr(field, 'required'):
+ required.append(field_name)
+
result_info = {
'type': 'object',
'title': model.__name__,
'description': model.__doc__,
- 'properties': {k: _map_schematics_type(v) for k, v in fields}
+ 'properties': properties
}
- required = [k for k, v in fields if getattr(v, 'required')]
if required:
result_info['required'] = required
-
return result_info
|
AlexisBRENON__ewmh_m2m-15
|
[
{
"changes": {
"added_entities": [
"src/ewmh_m2m/geometry.py:Geometry.horizontally_overlap",
"src/ewmh_m2m/geometry.py:Geometry.vertically_overlap",
"src/ewmh_m2m/geometry.py:Geometry.overlap"
],
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"src/ewmh_m2m/geometry.py:Geometry"
]
},
"file": "src/ewmh_m2m/geometry.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/ewmh_m2m/screen.py:get_sibling_screens"
],
"edited_modules": [
"src/ewmh_m2m/screen.py:get_sibling_screens"
]
},
"file": "src/ewmh_m2m/screen.py"
}
] |
AlexisBRENON/ewmh_m2m
|
c70bb48fd102fc526112f4cfb7c33ae157d83037
|
No sibling screen found - Error
Thanks for the great script! Unfortunately this is what I get:
$ move-to-monitor -v -v
DEBUG:ewmh_m2m.__main__:Detected screens: {Geometry(2960, 0, 1920, 1200), Geometry(0, 176, 1280, 1024), Geometry(1280, 150, 1680, 1050)}
DEBUG:ewmh_m2m.__main__:Containing screen: Geometry(0, 176, 1280, 1024)
CRITICAL:ewmh_m2m.__main__:No sibling screen found
This is my screen configuration:

Any suggestions?
|
diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml
index 49e0dde..e6b449e 100644
--- a/.github/workflows/python.yml
+++ b/.github/workflows/python.yml
@@ -19,7 +19,7 @@ jobs:
- name: Set up pip
run: |
python -m pip install --upgrade pip
- pip install --upgrade setuptools
+ pip install --upgrade setuptools wheel
- name: Install
run: pip install '.[testing]'
- name: Test with pytest
@@ -38,7 +38,7 @@ jobs:
- name: Set up pip
run: |
python -m pip install --upgrade pip
- pip install --upgrade setuptools
+ pip install --upgrade setuptools wheel
- name: Install
run: pip install '.[releasing]'
- name: Build
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 9bc9eb1..3dbbed3 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -2,6 +2,11 @@
Changelog
=========
+Version 1.1.3
+=============
+
+- Detect siblings screens even if not aligned with the current one
+
Version 1.1.2
=============
diff --git a/src/ewmh_m2m/geometry.py b/src/ewmh_m2m/geometry.py
index 7751d48..706fbf8 100644
--- a/src/ewmh_m2m/geometry.py
+++ b/src/ewmh_m2m/geometry.py
@@ -30,6 +30,15 @@ class Geometry:
y=int(container.y + self.y * container.h)
)
+ def horizontally_overlap(self, other) -> bool:
+ return self.y < other.y + other.h and self.y + self.h > other.y
+
+ def vertically_overlap(self, other) -> bool:
+ return self.x < other.x + other.w and self.x + self.w > other.x
+
+ def overlap(self, other) -> bool:
+ return self.horizontally_overlap(other) and self.vertically_overlap(other)
+
def __eq__(self, other):
return list(self) == list(other)
diff --git a/src/ewmh_m2m/screen.py b/src/ewmh_m2m/screen.py
index e9e340b..d2f050f 100644
--- a/src/ewmh_m2m/screen.py
+++ b/src/ewmh_m2m/screen.py
@@ -17,8 +17,8 @@ def get_sibling_screens(current: Geometry, screens: Iterable[Geometry]) -> Dict[
Each list is ordered from the nearest screen to the furthest one.
"""
- horizontal_screens = [g for g in screens if g.y == current.y]
- vertical_screens = [g for g in screens if g.x == current.x]
+ horizontal_screens = [g for g in screens if current.horizontally_overlap(g)]
+ vertical_screens = [g for g in screens if current.vertically_overlap(g)]
return {
Ordinal.SOUTH: sorted([g for g in vertical_screens if g.y > current.y], key=lambda g: g.y),
Ordinal.NORTH: sorted([g for g in vertical_screens if g.y < current.y], key=lambda g: -1 * g.y),
|
Algebra8__pyopenapi3-80
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/pyopenapi3/builders.py:PathItemBuilder.__call__",
"src/pyopenapi3/builders.py:ParamBuilder.__init__",
"src/pyopenapi3/builders.py:ComponentBuilder.__call__",
"src/pyopenapi3/builders.py:ComponentBuilder._parameters"
],
"edited_modules": [
"src/pyopenapi3/builders.py:PathItemBuilder",
"src/pyopenapi3/builders.py:ParamBuilder",
"src/pyopenapi3/builders.py:ComponentBuilder"
]
},
"file": "src/pyopenapi3/builders.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/pyopenapi3/utils.py:parse_name_and_type_from_fmt_str",
"src/pyopenapi3/utils.py:create_schema"
],
"edited_modules": [
"src/pyopenapi3/utils.py:parse_name_and_type_from_fmt_str",
"src/pyopenapi3/utils.py:create_schema"
]
},
"file": "src/pyopenapi3/utils.py"
}
] |
Algebra8/pyopenapi3
|
2237b16747c446adc2b67a080040f222c0493653
|
Make parse_name_and_type_from_fmt_str return reference to components
`pyopenapi3.utils.parse_name_and_type_from_fmt_str` should be able to accept the following format: `{name:Component}`.
Currently, it will only consider data types:
```
# In parse_name_and_type_from_fmt_str
yield arg_name, getattr(pyopenapi3.data_types, _type_name)
```
Take the following example:
```
@open_bldr.path
class PetsWithId:
path = "/pets/{pet_id:PetId}"
@open_bldr.component.parameter
class PetId:
name = "pet_id"
description = "Pet's Unique Identifier"
in_field = "path"
schema = create_schema(String, pattern="^[a-zA-Z0-9-]+$")
required = True
```
Here, `PetId` is a parameter component, and should be referenced. In this scenario `parse_name_and_type_from_fmt_str` should yield `'pet_id', create_reference("PetId")`
|
diff --git a/.gitignore b/.gitignore
index 8b5025d..45bfdbc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@ __pycache__/
pyopenapi3.egg-info/
dist/
build/
+.vscode/
diff --git a/src/pyopenapi3/builders.py b/src/pyopenapi3/builders.py
index 2fce8e4..c393181 100644
--- a/src/pyopenapi3/builders.py
+++ b/src/pyopenapi3/builders.py
@@ -3,6 +3,7 @@ from typing import get_type_hints, Union, List, Any, Dict, Optional
from collections import deque
import re
+from pyopenapi3.data_types import Component
from pyopenapi3.utils import (
build_mediatype_schema_from_content,
create_schema,
@@ -12,7 +13,7 @@ from pyopenapi3.utils import (
)
from pyopenapi3.objects import (
Response,
- RequestBody,
+ RequestBody
)
from pyopenapi3.schemas import (
RequestBodyObject,
@@ -212,6 +213,12 @@ class OperationBuilder:
)
+# Issue-75: Save any user defined Component schema so that it can
+# be validated and potentially referenced by `PathItemBuilder`.
+# See call to `parse_name_and_type_from_fmt_str` in `PathItemBuilder`.
+_allowed_types: Dict[str, Component] = {}
+
+
class PathItemBuilder:
def __init__(self):
@@ -248,7 +255,9 @@ class PathItemBuilder:
parameters += getattr(cls, 'parameters')
# The given path may also hold params, e.g. "/users/{id:Int64}"
path = cls.path
- for name, _type in parse_name_and_type_from_fmt_str(path):
+ for name, _type in parse_name_and_type_from_fmt_str(
+ path, allowed_types=_allowed_types
+ ):
parameters.append(
ParamBuilder('path').build_param(
name=name, schema=_type, required=True
@@ -269,8 +278,14 @@ class ParamBuilder:
_field_keys = set(ParameterObject.__fields__.keys())
_field_keys.add('schema')
+ _allowable_in_fields = {'path', 'query', 'header', 'cookie'}
def __init__(self, __in):
+ if __in not in self._allowable_in_fields:
+ raise ValueError(
+ f"{__in} is not an acceptable `in-field`. "
+ f"Choices are {list(self._allowable_in_fields)}"
+ )
self.__in = __in
def __call__(self, **kwargs):
@@ -420,7 +435,6 @@ class ComponentBuilder:
self._fields_used = set()
# Parameter builds
- # TODO parameters building for Comps
self.parameter = self._parameters
self._parameter_builds = {}
@@ -484,14 +498,18 @@ class ComponentBuilder:
# Flush functions that were used to build this ObjectSchema.
self._field_builds = {}
- injected_comp_cls = inject_component(cls)
- return injected_comp_cls
+ return inject_component(cls)
def _parameters(self, cls=None, /, *, as_dict=None):
if cls is not None:
self._parameter_builds[cls.__name__] = \
ParamBuilder.build_param_from_cls(cls)
- return cls
+
+ injected_comp_cls = inject_component(cls)
+ # Allow `cls` to be a valid reference in formatted `path`
+ # on `PathItemBuilder`
+ _allowed_types[cls.__name__] = injected_comp_cls
+ return injected_comp_cls
if as_dict is None:
raise ValueError(
"When not using the Components' parameter builder as a "
@@ -548,7 +566,7 @@ class ComponentBuilder:
return func
# Note, there is no good reason for why we can't just dump
- # the functions and any attrs (i.e. {} or kwargs), onto a
+ # the functions and any attrs (i.e. {} or kwargs), into a
# dict hosted by ComponentsBuilder, and flushing the dict
# after using it (note this is important, or else fields on
# older components will be used for the current iteration).
diff --git a/src/pyopenapi3/utils.py b/src/pyopenapi3/utils.py
index 74f61fd..ae92335 100644
--- a/src/pyopenapi3/utils.py
+++ b/src/pyopenapi3/utils.py
@@ -28,6 +28,7 @@ from .data_types import (
# _from_fmt_str`
import pyopenapi3.data_types
from .schemas import (
+ Schema,
StringDTSchema, ByteDTSchema, BinaryDTSchema, DateDTSchema,
DateTimeDTSchema, PasswordDTSchema, IntegerDTSchema, Int32DTSchema,
Int64DTSchema, NumberDTSchema, FloatDTSchema, DoubleDTSchema,
@@ -104,12 +105,31 @@ def format_description(s: Optional[str]) -> Optional[str]:
def parse_name_and_type_from_fmt_str(
- formatted_str) -> Generator[Tuple[str, Type[Field]], None, None]:
+ formatted_str: str,
+ allowed_types: Optional[Dict[str, Component]] = None
+) -> Generator[Tuple[str, Union[Type[Field], str]], None, None]:
"""
- Parse a formatted string and return the names
- of the args and their types.
+ Parse a formatted string and return the names of the args
+ and their types. Will raise a ValueError if the type is not
+ a pyopenapi3 `Field` or an already defined Component Parameter
+ type.
- E.g. "/user/{id:int}" -> ("id", "int")
+ In the case that the type represents a `Field`, then its
+ type will be returned, respectively. Otherwise, if it is an
+ already defined Component Parameter, then the name of the
+ class that defines the parameter will be returned.
+
+ .. code:: none
+ # E.g. 1
+
+ "/user/{id:String}" -> ("id", pyopenapi3.data_types.String)
+
+ # E.g. 2
+
+ @open_bldr.component.parameter
+ class PetId: ...
+
+ "/pets/{pet:PetId}" -> ("pet", "PetId")
If the string is not formatted, then will return (None, None).
"""
@@ -117,11 +137,19 @@ def parse_name_and_type_from_fmt_str(
if arg_name is not None:
try:
assert _type_name is not None
- yield arg_name, getattr(pyopenapi3.data_types, _type_name)
+ _type = (
+ allowed_types[_type_name] if allowed_types is not None
+ and _type_name in allowed_types
+ else getattr(pyopenapi3.data_types, _type_name)
+ )
+ yield arg_name, _type
except AttributeError:
raise ValueError(
"A non-`Field` or `OpenApiObject` type was found. "
- f"Can't use `{_type_name}` as a type in {formatted_str}."
+ f"Can't use `{_type_name}` as a type in {formatted_str}. "
+ f"Must be a stringified pyopenapi3 `data_type`, such "
+ f"as `pyopenapi3.data_types.String`, or a reference to a "
+ f"Component."
) from None
@@ -143,6 +171,10 @@ def create_schema(
__type: Type[OpenApiObject],
**kwargs: Any
) -> Union[SchemaObject, ReferenceObject]:
+ if isinstance(__type, Schema):
+ # Case where a Schema is already defined, don't need
+ # to recreate it.
+ return __type
if issubclass(__type, Component):
return convert_objects_to_schema(__type)
elif issubclass(__type, Primitive):
|
Algebra8__pyopenapi3-83
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"src/pyopenapi3/schemas.py:ObjectsDTSchema"
]
},
"file": "src/pyopenapi3/schemas.py"
}
] |
Algebra8/pyopenapi3
|
2ef34c3213eb292703e0e5e6f2185b1e4725bbde
|
Allow Free-Form Objects
Consider the following example:
```
definitions:
Pet:
type: object
properties:
tags:
type: object
description: Custom tags
```
According to [Open API 3 specs on data types](https://swagger.io/docs/specification/data-models/data-types/#object), "a free-form object (arbitrary property/value pairs) is defined as: `type: object`. This is equivalent to `type: object, additionalProperties: true` and `type: object, additionalProperties: {}`."
Free form objects should be allowed.
|
diff --git a/src/pyopenapi3/schemas.py b/src/pyopenapi3/schemas.py
index 141822f..daa78f6 100644
--- a/src/pyopenapi3/schemas.py
+++ b/src/pyopenapi3/schemas.py
@@ -164,7 +164,9 @@ class DTSchema(SchemaObject):
class ObjectsDTSchema(DTSchema):
type: str = Field('object', const=True)
- properties: Dict[str, Union[ReferenceObject, SchemaObject]]
+
+ # Optional to allow Free-Form objects. See issue-82.
+ properties: Optional[Dict[str, Union[ReferenceObject, SchemaObject]]]
class PrimitiveDTSchema(DTSchema):
|
Algebra8__pyopenapi3-91
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/pyopenapi3/builders.py:ComponentBuilder.__call__",
"src/pyopenapi3/builders.py:ComponentBuilder._parameters"
],
"edited_modules": [
"src/pyopenapi3/builders.py:ComponentBuilder"
]
},
"file": "src/pyopenapi3/builders.py"
},
{
"changes": {
"added_entities": null,
"added_modules": [
"src/pyopenapi3/data_types.py:Schemas",
"src/pyopenapi3/data_types.py:Parameters"
],
"edited_entities": null,
"edited_modules": null
},
"file": "src/pyopenapi3/data_types.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/pyopenapi3/utils.py:create_reference",
"src/pyopenapi3/utils.py:mark_component_and_attach_schema",
"src/pyopenapi3/utils.py:convert_objects_to_schema",
"src/pyopenapi3/utils.py:inject_component"
],
"edited_modules": [
"src/pyopenapi3/utils.py:create_reference",
"src/pyopenapi3/utils.py:mark_component_and_attach_schema",
"src/pyopenapi3/utils.py:convert_objects_to_schema",
"src/pyopenapi3/utils.py:inject_component"
]
},
"file": "src/pyopenapi3/utils.py"
}
] |
Algebra8/pyopenapi3
|
1637ca6ab3186f73baaf37b09594f59a745f63bb
|
Unresolvable pointer due to wrong reference
Consider the following example:
```
@component.parameter
class PetId:
name = "pet_id"
description = "Pet's Unique Identifier"
in_field = "path"
schema = create_schema(String, pattern="^[a-zA-Z0-9-]+$")
required = True
@open_bldr.path
class PetsWithId:
path = "/pets/{pet_id:PetId}"
```
The output of this build, in json (arbitrary), will be the following:
```
...
"parameters": [
{
"name": "pet_id",
"in": "path",
"required": true,
"schema": {
"$ref": "#/components/schemas/PetId"
}
}
]
...
```
However, its definition will not be in `components/schemas`, it will be in `components/parameters`:
```
"components":
...
"parameters": {
"PetId": {
"name": "pet_id",
"in": "path",
"description": "Pet's Unique Identifier",
"required": true,
"schema": {
"pattern": "^[a-zA-Z0-9-]+$",
"type": "string"
}
...
```
Need to make this reference point to parameters.
|
diff --git a/src/pyopenapi3/builders.py b/src/pyopenapi3/builders.py
index 164f041..a4b1663 100644
--- a/src/pyopenapi3/builders.py
+++ b/src/pyopenapi3/builders.py
@@ -5,7 +5,7 @@ import re
import yaml
-from pyopenapi3.data_types import Component
+from pyopenapi3.data_types import Component, Parameters, Schemas
from pyopenapi3.utils import (
build_mediatype_schema_from_content,
create_schema,
@@ -500,14 +500,14 @@ class ComponentBuilder:
# Flush functions that were used to build this ObjectSchema.
self._field_builds = {}
- return inject_component(cls)
+ return inject_component(cls, cmp_type=Schemas)
def _parameters(self, cls=None, /, *, as_dict=None):
if cls is not None:
self._parameter_builds[cls.__name__] = \
ParamBuilder.build_param_from_cls(cls)
- injected_comp_cls = inject_component(cls)
+ injected_comp_cls = inject_component(cls, cmp_type=Parameters)
# Allow `cls` to be a valid reference in formatted `path`
# on `PathItemBuilder`
_allowed_types[cls.__name__] = injected_comp_cls
diff --git a/src/pyopenapi3/data_types.py b/src/pyopenapi3/data_types.py
index 530f886..bdb8bab 100644
--- a/src/pyopenapi3/data_types.py
+++ b/src/pyopenapi3/data_types.py
@@ -151,3 +151,29 @@ class Object(Primitive):
# Components (Custom defined objects)
class Component(OpenApiObject):
...
+
+
+class Schemas(Component):
+ """Schema component type.
+
+ Note, the name of this class is important, as it will
+ determine the composition the Components schema.
+
+ I.e.:
+
+ "components":
+ "schemas": ...
+ """
+
+
+class Parameters(Component):
+ """Parameter component type.
+
+ Note, the name of this class is important, as it will
+ determine the composition the Components schema.
+
+ I.e.:
+
+ "components":
+ "parameters": ...
+ """
diff --git a/src/pyopenapi3/utils.py b/src/pyopenapi3/utils.py
index 557bcc2..ff70d52 100644
--- a/src/pyopenapi3/utils.py
+++ b/src/pyopenapi3/utils.py
@@ -10,7 +10,8 @@ from typing import (
Dict,
List,
Generator,
- Iterable
+ Iterable,
+ TypeVar
)
from string import Formatter
@@ -22,7 +23,7 @@ from .data_types import (
Array,
Field,
Primitive,
- Component
+ Component,
)
# Used to dynamically retrieve field in `parse_name_and_type
# _from_fmt_str`
@@ -56,9 +57,6 @@ from .schemas import (
)
-OPENAPI_DEF = '__OPENAPIDEF__FIELD_OR_COMPONENT__'
-
-
class _ObjectToDTSchema:
# Strings
@@ -167,18 +165,11 @@ def parse_name_and_type_from_fmt_str(
) from None
-def create_reference(name: str) -> ReferenceObject:
- return ReferenceObject(ref=f"#/components/schemas/{name}")
-
-
-def mark_component_and_attach_schema(obj, schema):
- """Mark an object as relating to an Open API schema
- and attach said schema to it.
-
- This will be used by `create_object` to build the entire
- `ObjectSchema`.
- """
- setattr(obj, OPENAPI_DEF, schema)
+def create_reference(
+ name: str,
+ component_dir: str = "schemas"
+) -> ReferenceObject:
+ return ReferenceObject(ref=f"#/components/{component_dir}/{name}")
def create_schema(
@@ -201,9 +192,19 @@ def create_schema(
def convert_objects_to_schema(obj: Type[Component]) -> ReferenceObject:
- # Any non-reference object should be created by the
- # Components builder.
- return create_reference(obj.__name__)
+ """Convert a custom object to a schema.
+
+ This is done by create a reference to the object. Any non-reference
+ object should be created by the Components builder.
+
+ param `obj` **must** be a subtype of `data_types.Component`. Its
+ type will determine what kind of component it is, e.g. '#/components/
+ schemas/...' or '#/components/parameters/...'.
+ """
+ cmp_type: str = 'schemas' # default component type
+ if hasattr(obj, '__cmp_type__'):
+ cmp_type = obj.__cmp_type__.lower() # type: ignore
+ return create_reference(obj.__name__, cmp_type)
def convert_primitive_to_schema(
@@ -232,22 +233,25 @@ def convert_array_to_schema(
return schema_type(items=sub_schemas[0], **kwargs)
-def inject_component(cls):
+ComponentType = TypeVar('ComponentType', bound=Component)
+
+
+def inject_component(cls, cmp_type: Type[ComponentType]):
"""'Inject' the `Component` class into the custom, user defined,
soon-to-be Component, class.
This will help when building a property that involves a user defined
custom Component.
+
+ param `cmp_type` is some subtype of `data_types.Component`, e.g.
+ whether it is a Schema component or Parameter component.
"""
if issubclass(cls, Component):
return cls
else:
- # @functools.wraps(cls, updated=())
- # class Injected(cls, Component):
- # pass
injected = type(
"Injected",
- (cls, Component),
+ (cls, cmp_type),
{attr_name: attr for attr_name, attr in cls.__dict__.items()}
)
injected.__qualname__ = f'Component[{cls.__name__}]'
@@ -255,6 +259,7 @@ def inject_component(cls):
# used in the conversion to an Open API object, e.g.
# {__name__: <rest of properties>}.
injected.__name__ = cls.__name__
+ injected.__cmp_type__ = cmp_type.__name__ # type: ignore
return injected
|
Algebra8__pyopenapi3-92
|
[
{
"changes": {
"added_entities": [
"examples/connexion_example/ex.py:get_pets",
"examples/connexion_example/ex.py:get_pet",
"examples/connexion_example/ex.py:put_get",
"examples/connexion_example/ex.py:delete_pet"
],
"added_modules": [
"examples/connexion_example/ex.py:get_pets",
"examples/connexion_example/ex.py:get_pet",
"examples/connexion_example/ex.py:put_get",
"examples/connexion_example/ex.py:delete_pet"
],
"edited_entities": null,
"edited_modules": [
"examples/connexion_example/ex.py:Pets",
"examples/connexion_example/ex.py:PetsWithId"
]
},
"file": "examples/connexion_example/ex.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/pyopenapi3/builders.py:ParamBuilder.build_param"
],
"edited_modules": [
"src/pyopenapi3/builders.py:ParamBuilder"
]
},
"file": "src/pyopenapi3/builders.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"src/pyopenapi3/utils.py:parse_name_and_type_from_fmt_str"
],
"edited_modules": [
"src/pyopenapi3/utils.py:parse_name_and_type_from_fmt_str"
]
},
"file": "src/pyopenapi3/utils.py"
}
] |
Algebra8/pyopenapi3
|
2f282f7f121550c845f77b16076b2bdf9b0b379f
|
Add connexion structure to /examples directory
Include everything that is required to make a simple connexion example work around #62, such as `app.py`.
|
diff --git a/examples/connexion_example/ex.py b/examples/connexion_example/app.py
similarity index 62%
rename from examples/connexion_example/ex.py
rename to examples/connexion_example/app.py
index 18e2a3e..42b4eb3 100644
--- a/examples/connexion_example/ex.py
+++ b/examples/connexion_example/app.py
@@ -1,8 +1,24 @@
-from pyopenapi3 import OpenApiBuilder, create_schema
+"""Example usage of `connexion`.
+
+Connexion parts are taken from (https://github.com/hjacobs/connexion-
+example/blob/master/app.py).
+"""
+
+import os
+from typing import Optional, Dict, List, Any, Tuple, Union
+import datetime
+import logging
+from pathlib import Path
+import connexion
+from connexion import NoContent
+
+from pyopenapi3 import OpenApiBuilder, create_schema
from pyopenapi3.data_types import String, Int32, Array, DateTime, Object
from pyopenapi3.objects import Op, Response, RequestBody, JSONMediaType
+
+# pyopenapi3
open_bldr = OpenApiBuilder()
@@ -75,7 +91,7 @@ class Pets:
)
]
- @paths.op(tags=["Pets"], operation_id=["app.get_pets"])
+ @paths.op(tags=["Pets"], operation_id="app.get_pets")
@paths.query_param(
name="animal_type",
schema=create_schema(String, pattern="^[a-zA-Z0-9]*$")
@@ -108,7 +124,7 @@ class PetsWithId:
Response(status=404, description="Pet does not exist")
]
- @paths.op(tags=["Pets"], operation_id=["app.get_pet"])
+ @paths.op(tags=["Pets"], operation_id="app.get_pet")
def get(self) -> Op[..., get_responses]:
"""Get a single pet"""
@@ -124,7 +140,7 @@ class PetsWithId:
required=True
)
- @paths.op(tags=["Pets"], operation_id=["app.put_get"])
+ @paths.op(tags=["Pets"], operation_id="app.put_get")
def put(self) -> Op[put_body, put_responses]:
"""Create or update a pet"""
@@ -133,6 +149,71 @@ class PetsWithId:
Response(status=404, description="Pet does not exist")
]
- @paths.op(tags=["Pets"], operation_id=["app.delete_pet"])
+ @paths.op(tags=["Pets"], operation_id="app.delete_pet")
def delete(self) -> Op[..., delete_responses]:
"""Remove a pet"""
+
+
+# Connexion
+Pet = Dict[str, Any]
+Response = Tuple[str, int]
+
+PETS: Dict[str, Pet] = {}
+
+
+def get_pets(
+ limit: int,
+ animal_type: Optional[str] = None
+) -> Dict[str, List[Pet]]:
+ return {
+ 'pets': [
+ pet for pet in PETS.values()
+ if animal_type is None or
+ pet['animal_type'] == animal_type[:limit]
+ ]
+ }
+
+
+def get_pet(pet_id: str) -> Union[Pet, Response]:
+ return PETS.get(pet_id, False) or ('Not found', 404)
+
+
+def put_get(pet_id: str, pet: Pet) -> Response:
+ exists = pet_id in PETS
+ pet['id'] = pet_id
+
+ if exists:
+ logging.info(f'Updating pet {pet_id}..')
+ PETS[pet_id].update(pet)
+ else:
+ logging.info(f'Creating pet {pet_id}..')
+ pet['created'] = datetime.datetime.utcnow()
+ PETS[pet_id] = pet
+ return NoContent, (200 if exists else 201)
+
+
+def delete_pet(pet_id: str) -> Response:
+ if pet_id in PETS:
+ logging.info(f'Deleting pet {pet_id}..')
+ del PETS[pet_id]
+ return NoContent, 204
+ else:
+ return NoContent, 404
+
+
+logging.basicConfig(level=logging.INFO)
+app = connexion.App(__name__)
+
+s = 'swagger.yaml'
+swagger_dir = os.path.abspath(os.path.dirname(__file__))
+swagger_path = Path(swagger_dir) / s
+with open(swagger_path, 'w') as f:
+ f.write(open_bldr.yaml())
+
+app.add_api(s)
+application = app.app
+
+
+if __name__ == '__main__':
+ print("Beginning server...")
+ app.run(port=8080, server='gevent')
diff --git a/src/pyopenapi3/builders.py b/src/pyopenapi3/builders.py
index a4b1663..901819c 100644
--- a/src/pyopenapi3/builders.py
+++ b/src/pyopenapi3/builders.py
@@ -301,6 +301,11 @@ class ParamBuilder:
if 'schema' in kwargs:
schema = kwargs.pop('schema')
kwargs['schema'] = create_schema(schema)
+ # If the schema is a reference, then return
+ # the reference.
+ if type(schema) == type:
+ if issubclass(schema, Component):
+ return kwargs['schema']
elif 'content' in kwargs:
content = kwargs.pop('content')
kwargs['content'] = build_mediatype_schema_from_content(content)
diff --git a/src/pyopenapi3/utils.py b/src/pyopenapi3/utils.py
index ff70d52..b6bf5c1 100644
--- a/src/pyopenapi3/utils.py
+++ b/src/pyopenapi3/utils.py
@@ -119,7 +119,7 @@ def format_description(s: Optional[str]) -> Optional[str]:
def parse_name_and_type_from_fmt_str(
formatted_str: str,
allowed_types: Optional[Dict[str, Component]] = None
-) -> Generator[Tuple[str, Union[Type[Field], str]], None, None]:
+) -> Generator[Tuple[str, Type[Field]], None, None]:
"""
Parse a formatted string and return the names of the args
and their types. Will raise a ValueError if the type is not
@@ -141,7 +141,7 @@ def parse_name_and_type_from_fmt_str(
@open_bldr.component.parameter
class PetId: ...
- "/pets/{pet:PetId}" -> ("pet", "PetId")
+ "/pets/{pet:PetId}" -> ("pet", PetId)
If the string is not formatted, then will return (None, None).
"""
|
All-Hands-AI__OpenHands-4154
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"openhands/core/config/sandbox_config.py:SandboxConfig"
]
},
"file": "openhands/core/config/sandbox_config.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"openhands/runtime/builder/docker.py:DockerRuntimeBuilder.build"
],
"edited_modules": [
"openhands/runtime/builder/docker.py:DockerRuntimeBuilder"
]
},
"file": "openhands/runtime/builder/docker.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"openhands/runtime/client/runtime.py:EventStreamRuntime.__init__",
"openhands/runtime/client/runtime.py:EventStreamRuntime._init_container"
],
"edited_modules": [
"openhands/runtime/client/runtime.py:EventStreamRuntime"
]
},
"file": "openhands/runtime/client/runtime.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"openhands/runtime/plugins/jupyter/__init__.py:JupyterPlugin.initialize"
],
"edited_modules": [
"openhands/runtime/plugins/jupyter/__init__.py:JupyterPlugin"
]
},
"file": "openhands/runtime/plugins/jupyter/__init__.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"openhands/runtime/remote/runtime.py:RemoteRuntime.__init__"
],
"edited_modules": [
"openhands/runtime/remote/runtime.py:RemoteRuntime"
]
},
"file": "openhands/runtime/remote/runtime.py"
}
] |
All-Hands-AI/OpenHands
|
c8a933590ac9bd55aa333940bacd4e323eff34bc
|
[Bug]: Runtime failed to build due to Mamba Error
### Is there an existing issue for the same bug?
- [X] I have checked the troubleshooting document at https://docs.all-hands.dev/modules/usage/troubleshooting
- [X] I have checked the existing issues.
### Describe the bug
```
Traceback (most recent call last):
File "/openhands/miniforge3/bin/mamba", line 7, in <module>
from mamba.mamba import main
File "/openhands/miniforge3/lib/python3.11/site-packages/mamba/mamba.py", line 18, in <module>
from conda.cli.main import generate_parser, init_loggers
ImportError: cannot import name 'generate_parser' from 'conda.cli.main'
```
which cause the build to fail
### Current OpenHands version
```bash
I am experimenting on https://github.com/All-Hands-AI/OpenHands/pull/3985, but it should pretty much the same as main
```
### Installation and Configuration
```bash
make build
```
### Model and Agent
_No response_
### Operating System
_No response_
### Reproduction Steps
_No response_
### Logs, Errors, Screenshots, and Additional Context
```
...
Package Version Build Channel Size
─────────────────────────────────────────────────────────────────────────────────────
Install:
─────────────────────────────────────────────────────────────────────────────────────
+ _libgcc_mutex 0.1 conda_forge conda-forge
+ ca-certificates 2024.8.30 hbcca054_0 conda-forge
+ ld_impl_linux-64 2.40 hf3520f5_7 conda-forge
+ pybind11-abi 4 hd8ed1ab_3 conda-forge
+ python_abi 3.12 5_cp312 conda-forge
+ tzdata 2024a h8827d51_1 conda-forge
+ libgomp 14.1.0 h77fa898_1 conda-forge
+ _openmp_mutex 4.5 2_gnu conda-forge
+ libgcc 14.1.0 h77fa898_1 conda-forge
+ libexpat 2.6.3 h5888daf_0 conda-forge
+ libgcc-ng 14.1.0 h69a702a_1 conda-forge
+ libstdcxx 14.1.0 hc0a3c3a_1 conda-forge
+ openssl 3.3.2 hb9d3cd8_0 conda-forge
+ bzip2 1.0.8 h4bc722e_7 conda-forge
+ c-ares 1.32.3 h4bc722e_0 conda-forge
+ keyutils 1.6.1 h166bdaf_0 conda-forge
+ libev 4.33 hd590300_2 conda-forge
+ libffi 3.4.2 h7f98852_5 conda-forge
+ libiconv 1.17 hd590300_2 conda-forge
+ libnsl 2.0.1 hd590300_0 conda-forge
+ libstdcxx-ng 14.1.0 h4852527_1 conda-forge
+ libuuid 2.38.1 h0b41bf4_0 conda-forge
+ libxcrypt 4.4.36 hd590300_1 conda-forge
+ libzlib 1.3.1 h4ab18f5_1 conda-forge
+ lzo 2.10 hd590300_1001 conda-forge
+ ncurses 6.5 he02047a_1 conda-forge
+ reproc 14.2.4.post0 hd590300_1 conda-forge
+ xz 5.2.6 h166bdaf_0 conda-forge
+ fmt 10.2.1 h00ab1b0_0 conda-forge
+ icu 75.1 he02047a_0 conda-forge
+ libedit 3.1.20191231 he28a2e2_2 conda-forge
+ libnghttp2 1.58.0 h47da74e_1 conda-forge
+ libsolv 0.7.30 h3509ff9_0 conda-forge
+ libsqlite 3.46.1 hadc24fc_0 conda-forge
+ libssh2 1.11.0 h0841786_0 conda-forge
+ lz4-c 1.9.4 hcb278e6_0 conda-forge
+ readline 8.2 h8228510_1 conda-forge
+ reproc-cpp 14.2.4.post0 h59595ed_1 conda-forge
+ tk 8.6.13 noxft_h4845f30_101 conda-forge
+ yaml-cpp 0.8.0 h59595ed_0 conda-forge
+ zstd 1.5.6 ha6fb4c9_0 conda-forge
+ krb5 1.21.3 h659f571_0 conda-forge
+ libxml2 2.12.7 he7c6b58_4 conda-forge
+ python 3.12.6 hc5c86c4_1_cpython conda-forge
+ libarchive 3.7.4 hfca40fe_0 conda-forge
+ libcurl 8.10.1 hbbe4b11_0 conda-forge
+ menuinst 2.1.2 py312h7900ff3_1 conda-forge
+ archspec 0.2.3 pyhd8ed1ab_0 conda-forge
+ boltons 24.0.0 pyhd8ed1ab_0 conda-forge
+ brotli-python 1.1.0 py312h2ec8cdc_2 conda-forge
+ certifi 2024.8.30 pyhd8ed1ab_0 conda-forge
+ charset-normalizer 3.3.2 pyhd8ed1ab_0 conda-forge
+ colorama 0.4.6 pyhd8ed1ab_0 conda-forge
+ distro 1.9.0 pyhd8ed1ab_0 conda-forge
+ frozendict 2.4.4 py312h66e93f0_1 conda-forge
+ hpack 4.0.0 pyh9f0ad1d_0 conda-forge
+ hyperframe 6.0.1 pyhd8ed1ab_0 conda-forge
+ idna 3.10 pyhd8ed1ab_0 conda-forge
+ jsonpointer 3.0.0 py312h7900ff3_1 conda-forge
+ libmamba 1.5.9 h4cc3d14_0 conda-forge
+ packaging 24.1 pyhd8ed1ab_0 conda-forge
+ platformdirs 4.3.6 pyhd8ed1ab_0 conda-forge
+ pluggy 1.5.0 pyhd8ed1ab_0 conda-forge
+ pycosat 0.6.6 py312h98912ed_0 conda-forge
+ pycparser 2.22 pyhd8ed1ab_0 conda-forge
+ pysocks 1.7.1 pyha2e5f31_6 conda-forge
+ ruamel.yaml.clib 0.2.8 py312h98912ed_0 conda-forge
+ setuptools 74.1.2 pyhd8ed1ab_0 conda-forge
+ truststore 0.9.2 pyhd8ed1ab_0 conda-forge
+ wheel 0.44.0 pyhd8ed1ab_0 conda-forge
+ cffi 1.17.1 py312h06ac9bb_0 conda-forge
+ h2 4.1.0 pyhd8ed1ab_0 conda-forge
+ jsonpatch 1.33 pyhd8ed1ab_0 conda-forge
+ libmambapy 1.5.9 py312h7fb9e8e_0 conda-forge
+ pip 24.2 pyh8b19718_1 conda-forge
+ ruamel.yaml 0.18.6 py312h98912ed_0 conda-forge
+ tqdm 4.66.5 pyhd8ed1ab_0 conda-forge
+ zstandard 0.23.0 py312hef9b889_1 conda-forge
+ conda-package-streaming 0.10.0 pyhd8ed1ab_0 conda-forge
+ urllib3 2.2.3 pyhd8ed1ab_0 conda-forge
+ conda-package-handling 2.3.0 pyh7900ff3_0 conda-forge
+ requests 2.32.3 pyhd8ed1ab_0 conda-forge
+ conda 24.7.1 py312h7900ff3_0 conda-forge
+ conda-libmamba-solver 24.7.0 pyhd8ed1ab_0 conda-forge
+ mamba 1.5.9 py312h9460a1c_0 conda-forge
Summary:
Install: 85 packages
Total download: 0 B
─────────────────────────────────────────────────────────────────────────────────────
Transaction starting
Transaction finished
To activate this environment, use:
micromamba activate /openhands/miniforge3
Or to execute a single command in this environment, use:
micromamba run -p /openhands/miniforge3 mycommand
installation finished.
Warning: 'conda-forge' already in 'channels' list, moving to the bottom
Removing intermediate container 8a5d0a595e2d
---> 6b53437dc1db
Step 7/11 : RUN /openhands/miniforge3/bin/mamba install conda-forge::poetry python=3.11 -y
---> Running in 71c23bfe4fd5
Transaction
Prefix: /openhands/miniforge3
Updating specs:
- conda-forge::poetry
- python=3.11
- ca-certificates
- certifi
- openssl
Package Version Build Channel Size
─────────────────────────────────────────────────────────────────────────────────────────
Install:
─────────────────────────────────────────────────────────────────────────────────────────
+ expat 2.6.3 h6a678d5_0 pkgs/main 181kB
+ blas 1.0 openblas pkgs/main 47kB
+ libgfortran5 11.2.0 h1234567_1 pkgs/main 2MB
+ libgfortran-ng 11.2.0 h00389a5_1 pkgs/main 20kB
+ libopenblas 0.3.21 h043d6bf_0 pkgs/main 6MB
+ zlib 1.2.13 h4ab18f5_6 conda-forge 93kB
+ pcre2 10.42 hebb0a14_1 pkgs/main 1MB
+ sqlite 3.45.3 h5eee18b_0 pkgs/main 1MB
+ libglib 2.78.4 hdc74915_0 pkgs/main 2MB
+ glib-tools 2.78.4 h6a678d5_0 pkgs/main 118kB
+ python-fastjsonschema 2.20.0 pyhd8ed1ab_0 conda-forge 226kB
+ poetry-core 1.9.0 pyhd8ed1ab_0 conda-forge 227kB
+ tomlkit 0.13.2 pyha770c72_0 conda-forge 37kB
+ numpy-base 1.26.4 py311hbfb1bba_0 pkgs/main 9MB
+ more-itertools 10.3.0 py311h06a4308_0 pkgs/main 149kB
+ msgpack-python 1.0.3 py311hdb19cb5_0 pkgs/main 37kB
+ glib 2.78.4 h6a678d5_0 pkgs/main 520kB
+ zipp 3.17.0 py311h06a4308_0 pkgs/main 25kB
+ filelock 3.13.1 py311h06a4308_0 pkgs/main 25kB
+ distlib 0.3.8 py311h06a4308_0 pkgs/main 467kB
+ trove-classifiers 2023.10.18 py311h06a4308_0 pkgs/main 22kB
+ tomli 2.0.1 py311h06a4308_0 pkgs/main 31kB
+ shellingham 1.5.0 py311h06a4308_0 pkgs/main 21kB
+ pyproject_hooks 1.0.0 py311h06a4308_0 pkgs/main 25kB
+ pkginfo 1.10.0 py311h06a4308_0 pkgs/main 67kB
+ crashtest 0.4.1 py311h06a4308_0 pkgs/main 18kB
+ numpy 1.26.4 py311h24aa872_0 pkgs/main 11kB
+ dbus 1.13.18 hb2f20db_0 pkgs/main 516kB
+ importlib-metadata 7.0.1 py311h06a4308_0 pkgs/main 50kB
+ virtualenv 20.26.1 py311h06a4308_0 pkgs/main 4MB
+ cryptography 43.0.0 py311hdda0065_0 pkgs/main 2MB
+ rapidfuzz 3.5.2 py311h6a678d5_0 pkgs/main 2MB
+ cleo 2.1.0 py311h06a4308_0 pkgs/main 181kB
+ jeepney 0.7.1 pyhd3eb1b0_0 pkgs/main 39kB
+ ptyprocess 0.7.0 pyhd3eb1b0_2 pkgs/main 17kB
+ python-installer 0.7.0 pyhd3eb1b0_1 pkgs/main 257kB
+ jaraco.classes 3.2.1 pyhd3eb1b0_0 pkgs/main 9kB
+ importlib_metadata 7.0.1 hd3eb1b0_0 pkgs/main 9kB
+ pexpect 4.8.0 pyhd3eb1b0_3 pkgs/main 54kB
+ python-build 1.2.2 pyhd8ed1ab_0 conda-forge 25kB
+ secretstorage 3.3.1 py311h06a4308_1 pkgs/main 29kB
+ dulwich 0.21.3 py311h5eee18b_0 pkgs/main 998kB
+ requests-toolbelt 1.0.0 py311h06a4308_0 pkgs/main 92kB
+ cachecontrol 0.14.0 py311h06a4308_1 pkgs/main 46kB
+ keyring 24.3.1 py311h06a4308_0 pkgs/main 82kB
+ cachecontrol-with-filecache 0.14.0 py311h06a4308_1 pkgs/main 5kB
+ poetry 1.8.3 linux_pyha804496_1 conda-forge 167kB
+ poetry-plugin-export 1.8.0 pyhd8ed1ab_0 conda-forge 16kB
Change:
─────────────────────────────────────────────────────────────────────────────────────────
- ruamel.yaml.clib 0.2.8 py312h98912ed_0 conda-forge Cached
+ ruamel.yaml.clib 0.2.8 py311h5eee18b_0 pkgs/main 161kB
- pycosat 0.6.6 py312h98912ed_0 conda-forge Cached
+ pycosat 0.6.6 py311h5eee18b_1 pkgs/main 97kB
- menuinst 2.1.2 py312h7900ff3_1 conda-forge Cached
+ menuinst 2.1.2 py311h06a4308_0 pkgs/main 263kB
- cffi 1.17.1 py312h06ac9bb_0 conda-forge Cached
+ cffi 1.17.1 py311h1fdaa30_0 pkgs/main 322kB
Reinstall:
─────────────────────────────────────────────────────────────────────────────────────────
o wheel 0.44.0 pyhd8ed1ab_0 conda-forge Cached
o setuptools 74.1.2 pyhd8ed1ab_0 conda-forge Cached
o pip 24.2 pyh8b19718_1 conda-forge Cached
o truststore 0.9.2 pyhd8ed1ab_0 conda-forge Cached
o pysocks 1.7.1 pyha2e5f31_6 conda-forge Cached
o pycparser 2.22 pyhd8ed1ab_0 conda-forge Cached
o pluggy 1.5.0 pyhd8ed1ab_0 conda-forge Cached
o platformdirs 4.3.6 pyhd8ed1ab_0 conda-forge Cached
o packaging 24.1 pyhd8ed1ab_0 conda-forge Cached
o idna 3.10 pyhd8ed1ab_0 conda-forge Cached
o hyperframe 6.0.1 pyhd8ed1ab_0 conda-forge Cached
o hpack 4.0.0 pyh9f0ad1d_0 conda-forge Cached
o distro 1.9.0 pyhd8ed1ab_0 conda-forge Cached
o colorama 0.4.6 pyhd8ed1ab_0 conda-forge Cached
o charset-normalizer 3.3.2 pyhd8ed1ab_0 conda-forge Cached
o certifi 2024.8.30 pyhd8ed1ab_0 conda-forge Cached
o boltons 24.0.0 pyhd8ed1ab_0 conda-forge Cached
o archspec 0.2.3 pyhd8ed1ab_0 conda-forge Cached
o h2 4.1.0 pyhd8ed1ab_0 conda-forge Cached
o tqdm 4.66.5 pyhd8ed1ab_0 conda-forge Cached
o urllib3 2.2.3 pyhd8ed1ab_0 conda-forge Cached
o conda-package-streaming 0.10.0 pyhd8ed1ab_0 conda-forge Cached
o jsonpatch 1.33 pyhd8ed1ab_0 conda-forge Cached
o requests 2.32.3 pyhd8ed1ab_0 conda-forge Cached
o conda-package-handling 2.3.0 pyh7900ff3_0 conda-forge Cached
o conda-libmamba-solver 24.7.0 pyhd8ed1ab_0 conda-forge Cached
Upgrade:
─────────────────────────────────────────────────────────────────────────────────────────
- ca-certificates 2024.8.30 hbcca054_0 conda-forge Cached
+ ca-certificates 2024.9.24 h06a4308_0 pkgs/main 133kB
- xz 5.2.6 h166bdaf_0 conda-forge Cached
+ xz 5.4.6 h5eee18b_1 pkgs/main 659kB
- libxml2 2.12.7 he7c6b58_4 conda-forge Cached
+ libxml2 2.13.1 hfdd30dd_2 pkgs/main 757kB
- conda 24.7.1 py312h7900ff3_0 conda-forge Cached
+ conda 24.9.0 py311h06a4308_0 pkgs/main 1MB
Downgrade:
─────────────────────────────────────────────────────────────────────────────────────────
- libuuid 2.38.1 h0b41bf4_0 conda-forge Cached
+ libuuid 1.41.5 h5eee18b_0 pkgs/main 28kB
- icu 75.1 he02047a_0 conda-forge Cached
+ icu 73.1 h6a678d5_0 pkgs/main 27MB
- libzlib 1.3.1 h4ab18f5_1 conda-forge Cached
+ libzlib 1.2.13 h4ab18f5_6 conda-forge 62kB
- libsqlite 3.46.1 hadc24fc_0 conda-forge Cached
+ libsqlite 3.46.0 hde9e2c9_0 conda-forge 865kB
- libcurl 8.10.1 hbbe4b11_0 conda-forge Cached
+ libcurl 8.8.0 hca28451_1 conda-forge 410kB
- libsolv 0.7.30 h3509ff9_0 conda-forge Cached
+ libsolv 0.7.24 he621ea3_1 pkgs/main 502kB
- python 3.12.6 hc5c86c4_1_cpython conda-forge Cached
+ python 3.11.9 h955ad1f_0 pkgs/main 34MB
- libmamba 1.5.9 h4cc3d14_0 conda-forge Cached
+ libmamba 1.5.8 had39da4_0 conda-forge 2MB
- frozendict 2.4.4 py312h66e93f0_1 conda-forge Cached
+ frozendict 2.4.2 py311h06a4308_0 pkgs/main 38kB
- brotli-python 1.1.0 py312h2ec8cdc_2 conda-forge Cached
+ brotli-python 1.0.9 py311h6a678d5_8 pkgs/main 367kB
- ruamel.yaml 0.18.6 py312h98912ed_0 conda-forge Cached
+ ruamel.yaml 0.17.21 py311h5eee18b_0 pkgs/main 255kB
- zstandard 0.23.0 py312hef9b889_1 conda-forge Cached
+ zstandard 0.19.0 py311h5eee18b_0 pkgs/main 449kB
- jsonpointer 3.0.0 py312h7900ff3_1 conda-forge Cached
+ jsonpointer 2.1 pyhd3eb1b0_0 pkgs/main 9kB
- python_abi 3.12 5_cp312 conda-forge Cached
+ python_abi 3.11 2_cp311 conda-forge 5kB
- libmambapy 1.5.9 py312h7fb9e8e_0 conda-forge Cached
+ libmambapy 1.5.8 py311hf2555c7_0 conda-forge 311kB
- mamba 1.5.9 py312h9460a1c_0 conda-forge Cached
+ mamba 1.5.8 py311h3072747_0 conda-forge 67kB
Summary:
Install: 48 packages
Change: 4 packages
Reinstall: 26 packages
Upgrade: 4 packages
Downgrade: 16 packages
Total download: 104MB
─────────────────────────────────────────────────────────────────────────────────────────
Looking for: ['conda-forge::poetry', 'python=3.11']
Downloading and Extracting Packages: ...working... done
Preparing transaction: ...working... done
Verifying transaction: ...working... done
Executing transaction: ...working... done
Removing intermediate container 71c23bfe4fd5
---> e07c93afbda8
Step 8/11 : RUN if [ -d /openhands/code ]; then rm -rf /openhands/code; fi
---> Running in 13bd633e1905
Removing intermediate container 13bd633e1905
---> 172894098a49
Step 9/11 : COPY ./code /openhands/code
---> 7d7e9aa1e383
Step 10/11 : WORKDIR /openhands/code
---> Running in 35bca73c59ee
Removing intermediate container 35bca73c59ee
---> ce2e67b74866
Step 11/11 : RUN /openhands/miniforge3/bin/mamba run -n base poetry config virtualenvs.path /openhands/poetry && /openhands/miniforge3/bin/mamba run -n base poetry env use python3.11 && /openhands/miniforge3/bin/mamba run -n base poetry install --only main,runtime --no-interaction --no-root && apt-get update && /openhands/miniforge3/bin/mamba run -n base poetry run pip install playwright && /openhands/miniforge3/bin/mamba run -n base poetry run playwright install --with-deps chromium && echo "OH_INTERPRETER_PATH=$(/openhands/miniforge3/bin/mamba run -n base poetry run python -c "import sys; print(sys.executable)")" >> /etc/environment && /openhands/miniforge3/bin/mamba run -n base poetry cache clear --all . && chmod -R g+rws /openhands/poetry && mkdir -p /openhands/workspace && chmod -R g+rws,o+rw /openhands/workspace && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && /openhands/miniforge3/bin/mamba clean --all
---> Running in 0b64bd15c323
Traceback (most recent call last):
File "/openhands/miniforge3/bin/mamba", line 7, in <module>
from mamba.mamba import main
File "/openhands/miniforge3/lib/python3.11/site-packages/mamba/mamba.py", line 18, in <module>
from conda.cli.main import generate_parser, init_loggers
ImportError: cannot import name 'generate_parser' from 'conda.cli.main' (/openhands/miniforge3/lib/python3.11/site-packages/conda/cli/main.py)
The command '/bin/sh -c /openhands/miniforge3/bin/mamba run -n base poetry config virtualenvs.path /openhands/poetry && /openhands/miniforge3/bin/mamba run -n base poetry env use python3.11 && /openhands/miniforge3/bin/mamba run -n base poetry install --only main,runtime --no-interaction --no-root && apt-get update && /openhands/miniforge3/bin/mamba run -n base poetry run pip install playwright && /openhands/miniforge3/bin/mamba run -n base poetry run playwright install --with-deps chromium && echo "OH_INTERPRETER_PATH=$(/openhands/miniforge3/bin/mamba run -n base poetry run python -c "import sys; print(sys.executable)")" >> /etc/environment && /openhands/miniforge3/bin/mamba run -n base poetry cache clear --all . && chmod -R g+rws /openhands/poetry && mkdir -p /openhands/workspace && chmod -R g+rws,o+rw /openhands/workspace && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && /openhands/miniforge3/bin/mamba clean --all' returned a non-zero code: 1
```
|
diff --git a/.github/workflows/ghcr-build.yml b/.github/workflows/ghcr-build.yml
index 34824777..82c30d98 100644
--- a/.github/workflows/ghcr-build.yml
+++ b/.github/workflows/ghcr-build.yml
@@ -293,7 +293,7 @@ jobs:
SANDBOX_RUNTIME_CONTAINER_IMAGE=$image_name \
TEST_IN_CI=true \
RUN_AS_OPENHANDS=false \
- poetry run pytest -n 3 -raR --reruns 1 --reruns-delay 3 --cov=agenthub --cov=openhands --cov-report=xml -s ./tests/runtime
+ poetry run pytest -n 3 -raRs --reruns 2 --reruns-delay 5 --cov=agenthub --cov=openhands --cov-report=xml -s ./tests/runtime
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v4
env:
@@ -371,7 +371,7 @@ jobs:
SANDBOX_RUNTIME_CONTAINER_IMAGE=$image_name \
TEST_IN_CI=true \
RUN_AS_OPENHANDS=true \
- poetry run pytest -n 3 -raR --reruns 1 --reruns-delay 3 --cov=agenthub --cov=openhands --cov-report=xml -s ./tests/runtime
+ poetry run pytest -n 3 -raRs --reruns 2 --reruns-delay 5 --cov=agenthub --cov=openhands --cov-report=xml -s ./tests/runtime
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v4
env:
diff --git a/openhands/core/config/sandbox_config.py b/openhands/core/config/sandbox_config.py
index e6dc72d2..3f535a5f 100644
--- a/openhands/core/config/sandbox_config.py
+++ b/openhands/core/config/sandbox_config.py
@@ -18,6 +18,7 @@ class SandboxConfig:
enable_auto_lint: Whether to enable auto-lint.
use_host_network: Whether to use the host network.
initialize_plugins: Whether to initialize plugins.
+ force_rebuild_runtime: Whether to force rebuild the runtime image.
runtime_extra_deps: The extra dependencies to install in the runtime image (typically used for evaluation).
This will be rendered into the end of the Dockerfile that builds the runtime image.
It can contain any valid shell commands (e.g., pip install numpy).
@@ -43,6 +44,7 @@ class SandboxConfig:
)
use_host_network: bool = False
initialize_plugins: bool = True
+ force_rebuild_runtime: bool = False
runtime_extra_deps: str | None = None
runtime_startup_env_vars: dict[str, str] = field(default_factory=dict)
browsergym_eval_env: str | None = None
diff --git a/openhands/runtime/builder/docker.py b/openhands/runtime/builder/docker.py
index 72995510..56a759df 100644
--- a/openhands/runtime/builder/docker.py
+++ b/openhands/runtime/builder/docker.py
@@ -113,8 +113,8 @@ class DockerRuntimeBuilder(RuntimeBuilder):
raise subprocess.CalledProcessError(
return_code,
process.args,
- output=None,
- stderr=None,
+ output=process.stdout.read() if process.stdout else None,
+ stderr=process.stderr.read() if process.stderr else None,
)
except subprocess.CalledProcessError as e:
diff --git a/openhands/runtime/client/runtime.py b/openhands/runtime/client/runtime.py
index c665f668..c6bb3019 100644
--- a/openhands/runtime/client/runtime.py
+++ b/openhands/runtime/client/runtime.py
@@ -167,6 +167,7 @@ class EventStreamRuntime(Runtime):
self.base_container_image,
self.runtime_builder,
extra_deps=self.config.sandbox.runtime_extra_deps,
+ force_rebuild=self.config.sandbox.force_rebuild_runtime,
)
self.container = self._init_container(
sandbox_workspace_dir=self.config.workspace_mount_path_in_sandbox, # e.g. /workspace
@@ -273,7 +274,7 @@ class EventStreamRuntime(Runtime):
container = self.docker_client.containers.run(
self.runtime_container_image,
command=(
- f'/openhands/miniforge3/bin/mamba run --no-capture-output -n base '
+ f'/openhands/micromamba/bin/micromamba run -n openhands '
f'poetry run '
f'python -u -m openhands.runtime.client.client {self._container_port} '
f'--working-dir "{sandbox_workspace_dir}" '
diff --git a/openhands/runtime/plugins/jupyter/__init__.py b/openhands/runtime/plugins/jupyter/__init__.py
index b46714c2..48ee21db 100644
--- a/openhands/runtime/plugins/jupyter/__init__.py
+++ b/openhands/runtime/plugins/jupyter/__init__.py
@@ -28,7 +28,8 @@ class JupyterPlugin(Plugin):
'cd /openhands/code\n'
'export POETRY_VIRTUALENVS_PATH=/openhands/poetry;\n'
'export PYTHONPATH=/openhands/code:$PYTHONPATH;\n'
- '/openhands/miniforge3/bin/mamba run -n base '
+ 'export MAMBA_ROOT_PREFIX=/openhands/micromamba;\n'
+ '/openhands/micromamba/bin/micromamba run -n openhands '
'poetry run jupyter kernelgateway '
'--KernelGatewayApp.ip=0.0.0.0 '
f'--KernelGatewayApp.port={self.kernel_gateway_port}\n'
diff --git a/openhands/runtime/remote/runtime.py b/openhands/runtime/remote/runtime.py
index c121021e..be4a19bc 100644
--- a/openhands/runtime/remote/runtime.py
+++ b/openhands/runtime/remote/runtime.py
@@ -119,6 +119,7 @@ class RemoteRuntime(Runtime):
self.config.sandbox.base_container_image,
self.runtime_builder,
extra_deps=self.config.sandbox.runtime_extra_deps,
+ force_rebuild=self.config.sandbox.force_rebuild_runtime,
)
response = send_request(
@@ -144,8 +145,8 @@ class RemoteRuntime(Runtime):
start_request = {
'image': self.container_image,
'command': (
- f'/openhands/miniforge3/bin/mamba run --no-capture-output -n base '
- 'PYTHONUNBUFFERED=1 poetry run '
+ f'/openhands/micromamba/bin/micromamba run -n openhands '
+ 'poetry run '
f'python -u -m openhands.runtime.client.client {self.port} '
f'--working-dir {self.config.workspace_mount_path_in_sandbox} '
f'{plugin_arg}'
diff --git a/openhands/runtime/utils/runtime_templates/Dockerfile.j2 b/openhands/runtime/utils/runtime_templates/Dockerfile.j2
index 57ea62db..33958471 100644
--- a/openhands/runtime/utils/runtime_templates/Dockerfile.j2
+++ b/openhands/runtime/utils/runtime_templates/Dockerfile.j2
@@ -1,11 +1,13 @@
-{% if skip_init %}
FROM {{ base_image }}
-{% else %}
+
+# Shared environment variables (regardless of init or not)
+ENV POETRY_VIRTUALENVS_PATH=/openhands/poetry
+ENV MAMBA_ROOT_PREFIX=/openhands/micromamba
+
+{% if not skip_init %}
# ================================================================
# START: Build Runtime Image from Scratch
# ================================================================
-FROM {{ base_image }}
-
{% if 'ubuntu' in base_image and (base_image.endswith(':latest') or base_image.endswith(':24.04')) %}
{% set LIBGL_MESA = 'libgl1' %}
{% else %}
@@ -14,7 +16,7 @@ FROM {{ base_image }}
# Install necessary packages and clean up in one layer
RUN apt-get update && \
- apt-get install -y wget sudo apt-utils {{ LIBGL_MESA }} libasound2-plugins git && \
+ apt-get install -y wget curl sudo apt-utils {{ LIBGL_MESA }} libasound2-plugins git && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
@@ -26,19 +28,16 @@ RUN mkdir -p /openhands && \
mkdir -p /openhands/logs && \
mkdir -p /openhands/poetry
-# Directory containing subdirectories for virtual environment.
-ENV POETRY_VIRTUALENVS_PATH=/openhands/poetry
+# Install micromamba
+RUN mkdir -p /openhands/micromamba/bin && \
+ /bin/bash -c "PREFIX_LOCATION=/openhands/micromamba BIN_FOLDER=/openhands/micromamba/bin INIT_YES=no CONDA_FORGE_YES=yes $(curl -L https://micro.mamba.pm/install.sh)" && \
+ /openhands/micromamba/bin/micromamba config remove channels defaults && \
+ /openhands/micromamba/bin/micromamba config list
-RUN if [ ! -d /openhands/miniforge3 ]; then \
- wget --progress=bar:force -O Miniforge3.sh "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh" && \
- bash Miniforge3.sh -b -p /openhands/miniforge3 && \
- rm Miniforge3.sh && \
- chmod -R g+w /openhands/miniforge3 && \
- bash -c ". /openhands/miniforge3/etc/profile.d/conda.sh && conda config --set changeps1 False && conda config --append channels conda-forge"; \
- fi
+# Create the openhands virtual environment and install poetry and python
+RUN /openhands/micromamba/bin/micromamba create -n openhands -y && \
+ /openhands/micromamba/bin/micromamba install -n openhands -c conda-forge poetry python=3.11 -y
-# Install Python and Poetry
-RUN /openhands/miniforge3/bin/mamba install conda-forge::poetry python=3.11 -y
# ================================================================
# END: Build Runtime Image from Scratch
# ================================================================
@@ -59,27 +58,28 @@ COPY ./code /openhands/code
# virtual environment are used by default.
WORKDIR /openhands/code
RUN \
+ /openhands/micromamba/bin/micromamba config set changeps1 False && \
# Configure Poetry and create virtual environment
- /openhands/miniforge3/bin/mamba run -n base poetry config virtualenvs.path /openhands/poetry && \
- /openhands/miniforge3/bin/mamba run -n base poetry env use python3.11 && \
+ /openhands/micromamba/bin/micromamba run -n openhands poetry config virtualenvs.path /openhands/poetry && \
+ /openhands/micromamba/bin/micromamba run -n openhands poetry env use python3.11 && \
# Install project dependencies
- /openhands/miniforge3/bin/mamba run -n base poetry install --only main,runtime --no-interaction --no-root && \
+ /openhands/micromamba/bin/micromamba run -n openhands poetry install --only main,runtime --no-interaction --no-root && \
# Update and install additional tools
apt-get update && \
- /openhands/miniforge3/bin/mamba run -n base poetry run pip install playwright && \
- /openhands/miniforge3/bin/mamba run -n base poetry run playwright install --with-deps chromium && \
+ /openhands/micromamba/bin/micromamba run -n openhands poetry run pip install playwright && \
+ /openhands/micromamba/bin/micromamba run -n openhands poetry run playwright install --with-deps chromium && \
# Set environment variables
- echo "OH_INTERPRETER_PATH=$(/openhands/miniforge3/bin/mamba run -n base poetry run python -c "import sys; print(sys.executable)")" >> /etc/environment && \
+ echo "OH_INTERPRETER_PATH=$(/openhands/micromamba/bin/micromamba run -n openhands poetry run python -c "import sys; print(sys.executable)")" >> /etc/environment && \
# Install extra dependencies if specified
{{ extra_deps }} {% if extra_deps %} && {% endif %} \
# Clear caches
- /openhands/miniforge3/bin/mamba run -n base poetry cache clear --all . && \
+ /openhands/micromamba/bin/micromamba run -n openhands poetry cache clear --all . && \
# Set permissions
{% if not skip_init %}chmod -R g+rws /openhands/poetry && {% endif %} \
mkdir -p /openhands/workspace && chmod -R g+rws,o+rw /openhands/workspace && \
# Clean up
apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \
- /openhands/miniforge3/bin/mamba clean --all
+ /openhands/micromamba/bin/micromamba clean --all
# ================================================================
# END: Copy Project and Install/Update Dependencies
# ================================================================
|
All-Hands-AI__openhands-aci-17
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"openhands_aci/editor/editor.py:OHEditor.str_replace"
],
"edited_modules": [
"openhands_aci/editor/editor.py:OHEditor"
]
},
"file": "openhands_aci/editor/editor.py"
}
] |
All-Hands-AI/openhands-aci
|
b551afd07cc9d84ee0322c3334dae3bcd3ee00ea
|
[Bug]: Editing Error "No replacement was performed" is not informative enough
Cross post from https://github.com/All-Hands-AI/OpenHands/issues/5365
|
diff --git a/openhands_aci/editor/editor.py b/openhands_aci/editor/editor.py
index 0cbb0a1..e98354b 100644
--- a/openhands_aci/editor/editor.py
+++ b/openhands_aci/editor/editor.py
@@ -110,12 +110,17 @@ class OHEditor:
f'No replacement was performed, old_str `{old_str}` did not appear verbatim in {path}.'
)
if occurrences > 1:
- file_content_lines = file_content.split('\n')
- line_numbers = [
- idx + 1
- for idx, line in enumerate(file_content_lines)
- if old_str in line
- ]
+ # Find starting line numbers for each occurrence
+ line_numbers = []
+ start_idx = 0
+ while True:
+ idx = file_content.find(old_str, start_idx)
+ if idx == -1:
+ break
+ # Count newlines before this occurrence to get the line number
+ line_num = file_content.count('\n', 0, idx) + 1
+ line_numbers.append(line_num)
+ start_idx = idx + 1
raise ToolError(
f'No replacement was performed. Multiple occurrences of old_str `{old_str}` in lines {line_numbers}. Please ensure it is unique.'
)
|
All-Hands-AI__openhands-resolver-123
|
[
{
"changes": {
"added_entities": [
"openhands_resolver/send_pull_request.py:branch_exists"
],
"added_modules": [
"openhands_resolver/send_pull_request.py:branch_exists"
],
"edited_entities": [
"openhands_resolver/send_pull_request.py:send_pull_request"
],
"edited_modules": [
"openhands_resolver/send_pull_request.py:send_pull_request"
]
},
"file": "openhands_resolver/send_pull_request.py"
}
] |
All-Hands-AI/openhands-resolver
|
84ccb9b29d786c3cb16f100b31ee456ddc622fd0
|
Better handling of when a branch already exists
Currently, in `github_resolver/send_pull_request.py`, when pushing to github for a particular issue, the branch name is fixed here:
https://github.com/All-Hands-AI/openhands-resolver/blob/44aa2907d70852b7f98786c673304cc18b76d43e/openhands_resolver/send_pull_request.py#L162
However, if the github resolver has already tried to solve the issue and failed, the branch may already exist. Because of this, it would be better to check if the branch already exists, and if it does, further append `-try2`, `-try3`, until it finds a branch that doesn't exist.
|
diff --git a/openhands_resolver/send_pull_request.py b/openhands_resolver/send_pull_request.py
index dd227b7..3d06d3e 100644
--- a/openhands_resolver/send_pull_request.py
+++ b/openhands_resolver/send_pull_request.py
@@ -139,6 +139,11 @@ def make_commit(repo_dir: str, issue: GithubIssue) -> None:
raise RuntimeError("Failed to commit changes")
+
+def branch_exists(base_url: str, branch_name: str, headers: dict) -> bool:
+ response = requests.get(f"{base_url}/branches/{branch_name}", headers=headers)
+ return response.status_code == 200
+
def send_pull_request(
github_issue: GithubIssue,
github_token: str,
@@ -158,15 +163,21 @@ def send_pull_request(
}
base_url = f"https://api.github.com/repos/{github_issue.owner}/{github_issue.repo}"
- # Create a new branch
- branch_name = f"openhands-fix-issue-{github_issue.number}"
+ # Create a new branch with a unique name
+ base_branch_name = f"openhands-fix-issue-{github_issue.number}"
+ branch_name = base_branch_name
+ attempt = 1
+
+ while branch_exists(base_url, branch_name, headers):
+ attempt += 1
+ branch_name = f"{base_branch_name}-try{attempt}"
# Get the default branch
response = requests.get(f"{base_url}", headers=headers)
response.raise_for_status()
default_branch = response.json()["default_branch"]
- # Push changes to the new branch (using git command, as before)
+ # Create and checkout the new branch
result = subprocess.run(
f"git -C {patch_dir} checkout -b {branch_name}",
shell=True,
|
All-Hands-AI__openhands-resolver-124
|
[
{
"changes": {
"added_entities": [
"openhands_resolver/send_pull_request.py:main"
],
"added_modules": [
"openhands_resolver/send_pull_request.py:main"
],
"edited_entities": null,
"edited_modules": null
},
"file": "openhands_resolver/send_pull_request.py"
}
] |
All-Hands-AI/openhands-resolver
|
6a547e11e71659cd97f776157e68b21277b25359
|
Add end-to-end tests for `send_pull_request.py`
Currently, there are no tests to make sure that argument parsing, etc. are working properly in `openhands_resolver/send_pull_request.py`.
In order to fix this, we can do the following:
1. Move the entirety of the content after `if __name__ == "__main__":` to a new `main()` function.
2. Add tests to `tests/test_send_pull_request.py` that make sure that given a certain set of command line arguments, this `main()` function runs correctly
|
diff --git a/openhands_resolver/send_pull_request.py b/openhands_resolver/send_pull_request.py
index 1b58e14..dd227b7 100644
--- a/openhands_resolver/send_pull_request.py
+++ b/openhands_resolver/send_pull_request.py
@@ -285,7 +285,7 @@ def process_all_successful_issues(
)
-if __name__ == "__main__":
+def main():
parser = argparse.ArgumentParser(description="Send a pull request to Github.")
parser.add_argument(
"--github-token",
@@ -372,3 +372,6 @@ if __name__ == "__main__":
my_args.fork_owner,
my_args.send_on_failure,
)
+
+if __name__ == "__main__":
+ main()
|
All-Hands-AI__openhands-resolver-137
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "openhands_resolver/__init__.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"openhands_resolver/send_pull_request.py:make_commit",
"openhands_resolver/send_pull_request.py:process_single_issue"
],
"edited_modules": [
"openhands_resolver/send_pull_request.py:make_commit",
"openhands_resolver/send_pull_request.py:process_single_issue"
]
},
"file": "openhands_resolver/send_pull_request.py"
}
] |
All-Hands-AI/openhands-resolver
|
63dd2c9c905a375db53785c0a69e56951a279189
|
"Unterminated quoted string"
On a run of the github action, the following error was encountered:
```bash
Run if [ "true" == "true" ]; then
Traceback (most recent call last):
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "/opt/hostedtoolcache/Python/3.11.10/x64/lib/python3.11/site-packages/openhands_resolver/send_pull_request.py", line 388, in <module>
main()
File "/opt/hostedtoolcache/Python/3.11.10/x64/lib/python3.11/site-packages/openhands_resolver/send_pull_request.py", line 377, in main
process_single_issue(
File "/opt/hostedtoolcache/Python/3.11.10/x64/lib/python3.11/site-packages/openhands_resolver/send_pull_request.py", line 264, in process_single_issue
make_commit(patched_repo_dir, resolver_output.issue)
File "/opt/hostedtoolcache/Python/3.11.10/x64/lib/python3.11/site-packages/openhands_resolver/send_pull_request.py", line 139, in make_commit
raise RuntimeError("Failed to commit changes")
RuntimeError: Failed to commit changes
Copied repository to output/patches/issue_20
Patch applied successfully
Git user configured as openhands
Error committing changes: /bin/sh: 1: Syntax error: Unterminated quoted string
```
The reason seems to be because in `openhands_resolver/send_pull_request.py`, the line here:
https://github.com/All-Hands-AI/openhands-resolver/blob/63dd2c9c905a375db53785c0a69e56951a279189/openhands_resolver/send_pull_request.py#L132
the `git commit` does not have `issue.title` properly escaped.
Once this is fixed, we should also bump the version to 0.1.6 and re-release.
|
diff --git a/openhands_resolver/__init__.py b/openhands_resolver/__init__.py
index 1276d02..0a8da88 100644
--- a/openhands_resolver/__init__.py
+++ b/openhands_resolver/__init__.py
@@ -1,1 +1,1 @@
-__version__ = "0.1.5"
+__version__ = "0.1.6"
diff --git a/openhands_resolver/send_pull_request.py b/openhands_resolver/send_pull_request.py
index 3d06d3e..ba24568 100644
--- a/openhands_resolver/send_pull_request.py
+++ b/openhands_resolver/send_pull_request.py
@@ -9,6 +9,7 @@ from openhands_resolver.io_utils import (
from openhands_resolver.patching import parse_patch, apply_diff
import requests
import subprocess
+import shlex
from openhands_resolver.resolver_output import ResolverOutput
@@ -128,8 +129,9 @@ def make_commit(repo_dir: str, issue: GithubIssue) -> None:
print(f"Error adding files: {result.stderr}")
raise RuntimeError("Failed to add files to git")
+ commit_message = f"Fix issue #{issue.number}: {shlex.quote(issue.title)}"
result = subprocess.run(
- f"git -C {repo_dir} commit -m 'Fix issue #{issue.number}: {issue.title}'",
+ f"git -C {repo_dir} commit -m {shlex.quote(commit_message)}",
shell=True,
capture_output=True,
text=True,
@@ -251,7 +253,7 @@ def process_single_issue(
) -> None:
if not resolver_output.success and not send_on_failure:
print(
- f"Issue {issue_number} was not successfully resolved. Skipping PR creation."
+ f"Issue {resolver_output.issue.number} was not successfully resolved. Skipping PR creation."
)
return
diff --git a/pyproject.toml b/pyproject.toml
index 2516498..005e349 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
[tool.poetry]
name = "openhands-resolver"
-version = "0.1.5"
+version = "0.1.6"
description = "OpenHands Issue Resolver"
authors = ["All Hands AI"]
license = "MIT"
|
Altran-PT-GDC__Robot-Framework-Mainframe-3270-Library-93
|
[
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": [
"Mainframe3270/x3270.py:x3270._process_args"
],
"edited_modules": [
"Mainframe3270/x3270.py:x3270"
]
},
"file": "Mainframe3270/x3270.py"
}
] |
Altran-PT-GDC/Robot-Framework-Mainframe-3270-Library
|
2b1b7717383044d4112e699e8cff5c456a4c9c49
|
Enable shell-like syntax for `extra_args` from file
With the current implementation of `x3270._process_args` arguments from a file are split by whitespaces, e.g.
```txt
# argfile.txt
-charset french
```
becomes ["-charset", "french"].
There are, however, resources that allow whitespace between the arguments, like -xrm "wc3270.blankFill: true". On a command line, the whitespace can be retained using single or double quotes. This is currently not possible with the implementation of `x3270._process_args`.
I would like something like
```txt
# argfile.txt
-xrm "wc3270.blankFill: true"
```
to be interpreted as ["-xrm", "wc3270.blankFill: true"]
|
diff --git a/Mainframe3270/x3270.py b/Mainframe3270/x3270.py
index 9b84413..b39724c 100644
--- a/Mainframe3270/x3270.py
+++ b/Mainframe3270/x3270.py
@@ -1,5 +1,6 @@
import os
import re
+import shlex
import socket
import time
from datetime import timedelta
@@ -64,12 +65,13 @@ class x3270(object):
`extra_args` accepts either a list or a path to a file containing [https://x3270.miraheze.org/wiki/Category:Command-line_options|x3270 command line options].
Entries in the argfile can be on one line or multiple lines. Lines starting with "#" are considered comments.
+ Arguments containing whitespace must be enclosed in single or double quotes.
| # example_argfile_oneline.txt
| -accepthostname myhost.com
| # example_argfile_multiline.txt
- | -accepthostname myhost.com
+ | -xrm "wc3270.acceptHostname: myhost.com"
| # this is a comment
| -charset french
| -port 992
@@ -117,7 +119,7 @@ class x3270(object):
for line in file:
if line.lstrip().startswith("#"):
continue
- for arg in line.replace("\n", "").rstrip().split(" "):
+ for arg in shlex.split(line):
processed_args.append(arg)
return processed_args
|
AmiiThinks__driving_gridworld-13
|
[
{
"changes": {
"added_entities": [
"driving_gridworld/road.py:Road.speed_limit"
],
"added_modules": null,
"edited_entities": [
"driving_gridworld/road.py:Road.__init__",
"driving_gridworld/road.py:Road.successors"
],
"edited_modules": [
"driving_gridworld/road.py:Road"
]
},
"file": "driving_gridworld/road.py"
}
] |
AmiiThinks/driving_gridworld
|
fbc47c68cfade4e7d95ba59a3990dfef196389a6
|
Enforce a hard limit on the speed limit in `Road` to the number of rows + 1
If the speed limit is larger than this, then the physical plausibility of the similar breaks, because the number of possible obstacle encounters across a fixed distance can depend on the car's speed and the range of its headlights (the number of rows).
|
diff --git a/driving_gridworld/road.py b/driving_gridworld/road.py
index cb519ef..559362f 100644
--- a/driving_gridworld/road.py
+++ b/driving_gridworld/road.py
@@ -142,13 +142,12 @@ def combinations(iterable, r, collection=tuple):
class Road(object):
- def __init__(self, num_rows, car, obstacles, speed_limit):
- if speed_limit < car.speed:
+ def __init__(self, num_rows, car, obstacles):
+ if num_rows + 1 < car.speed:
raise ValueError("Car's speed above speed limit!")
self._num_rows = num_rows
self._num_columns = 4
self._car = car
- self._speed_limit = speed_limit
self._obstacles = obstacles
self._available_spaces = {}
for pos in product(range(0, self._car.speed), range(4)):
@@ -159,6 +158,20 @@ class Road(object):
if disallowed_position in self._available_spaces:
del self._available_spaces[disallowed_position]
+ def speed_limit(self):
+ '''The hard speed limit on this road.
+
+ Taking the `UP` action when traveling at the speed limit has no effect.
+
+ Set according to the headlight range since overdriving the
+ headlights too much breaks the physical plausibility of the game
+ due to the way we reusing obstacles to simulate arbitrarily long
+ roads with many obstacles. This is not too much of a restriction
+ though because even overdriving the headlights by one unit is
+ completely unsafe.
+ '''
+ return self._num_rows + 1
+
def obstacle_outside_car_path(self, obstacle):
return (obstacle.col < 0 or obstacle.col >= self._num_columns
or obstacle.row >= self._num_rows)
@@ -198,7 +211,7 @@ class Road(object):
state. The reward function is deterministic.
'''
- next_car = self._car.next(action, self._speed_limit)
+ next_car = self._car.next(action, self.speed_limit())
for positions, reveal_indices in (
self.every_combination_of_revealed_obstacles()):
@@ -225,8 +238,7 @@ class Road(object):
reward += self._car.reward()
if self._car.col == 0 or self._car.col == 3:
reward -= 4 * self._car.speed
- next_road = self.__class__(self._num_rows, next_car,
- next_obstacles, self._speed_limit)
+ next_road = self.__class__(self._num_rows, next_car, next_obstacles)
yield (next_road, prob, reward)
def to_key(self, show_walls=False):
|
AnalogJ__lexicon-264
|
[
{
"changes": {
"added_entities": [
"lexicon/__main__.py:generate_table_result",
"lexicon/__main__.py:handle_output"
],
"added_modules": [
"lexicon/__main__.py:generate_table_result",
"lexicon/__main__.py:handle_output"
],
"edited_entities": [
"lexicon/__main__.py:BaseProviderParser",
"lexicon/__main__.py:MainParser",
"lexicon/__main__.py:main"
],
"edited_modules": [
"lexicon/__main__.py:BaseProviderParser",
"lexicon/__main__.py:MainParser",
"lexicon/__main__.py:main"
]
},
"file": "lexicon/__main__.py"
}
] |
AnalogJ/lexicon
|
59a1372a2ba31204f77a8383d0880ba62e0e6607
|
[CLI] Pretty output for list method
Is there any plans to have pretty outputs (table or at least formatted) for the ```list``` operation on the CLI?
Right now, the CLI assumes a verbosity of DEBUG level, and outputs the Python representation of the result (managed by the provider). If --log_level=ERROR is used, no output is generated, which defeats the CLI usage, in my opinion.
Is this behavior expected? Would you be open to a PR for that?
|
diff --git a/lexicon/__main__.py b/lexicon/__main__.py
index d674809e..ad243f18 100644
--- a/lexicon/__main__.py
+++ b/lexicon/__main__.py
@@ -7,6 +7,7 @@ import importlib
import logging
import os
import sys
+import json
import pkg_resources
@@ -19,16 +20,19 @@ logger = logging.getLogger(__name__)
def BaseProviderParser():
parser = argparse.ArgumentParser(add_help=False)
- parser.add_argument("action", help="specify the action to take", default='list', choices=['create', 'list', 'update', 'delete'])
- parser.add_argument("domain", help="specify the domain, supports subdomains as well")
- parser.add_argument("type", help="specify the entry type", default='TXT', choices=['A', 'AAAA', 'CNAME', 'MX', 'NS', 'SOA', 'TXT', 'SRV', 'LOC'])
-
- parser.add_argument("--name", help="specify the record name")
- parser.add_argument("--content", help="specify the record content")
- parser.add_argument("--ttl", type=int, help="specify the record time-to-live")
- parser.add_argument("--priority", help="specify the record priority")
- parser.add_argument("--identifier", help="specify the record for update or delete actions")
- parser.add_argument("--log_level", help="specify the log level", default="DEBUG", choices=["CRITICAL","ERROR","WARNING","INFO","DEBUG","NOTSET"])
+ parser.add_argument('action', help='specify the action to take', default='list', choices=['create', 'list', 'update', 'delete'])
+ parser.add_argument('domain', help='specify the domain, supports subdomains as well')
+ parser.add_argument('type', help='specify the entry type', default='TXT', choices=['A', 'AAAA', 'CNAME', 'MX', 'NS', 'SOA', 'TXT', 'SRV', 'LOC'])
+
+ parser.add_argument('--name', help='specify the record name')
+ parser.add_argument('--content', help='specify the record content')
+ parser.add_argument('--ttl', type=int, help='specify the record time-to-live')
+ parser.add_argument('--priority', help='specify the record priority')
+ parser.add_argument('--identifier', help='specify the record for update or delete actions')
+ parser.add_argument('--log_level', help='specify the log level', default='ERROR', choices=['CRITICAL','ERROR','WARNING','INFO','DEBUG','NOTSET'])
+ parser.add_argument('--output',
+ help='specify the type of output: by default a formatted table (TABLE), a formatted table without header (TABLE-NO-HEADER), a JSON string (JSON) or no output (QUIET)',
+ default='TABLE', choices=['TABLE', 'TABLE-NO-HEADER', 'JSON', 'QUIET'])
return parser
def MainParser():
@@ -43,11 +47,11 @@ def MainParser():
parser = argparse.ArgumentParser(description='Create, Update, Delete, List DNS entries')
try:
- version = pkg_resources.get_distribution("dns-lexicon").version
+ version = pkg_resources.get_distribution('dns-lexicon').version
except pkg_resources.DistributionNotFound:
version = 'unknown'
- parser.add_argument('--version', help="show the current version of lexicon", action='version', version='%(prog)s {0}'.format(version))
- parser.add_argument('--delegated', help="specify the delegated domain")
+ parser.add_argument('--version', help='show the current version of lexicon', action='version', version='%(prog)s {0}'.format(version))
+ parser.add_argument('--delegated', help='specify the delegated domain')
subparsers = parser.add_subparsers(dest='provider_name', help='specify the DNS provider to use')
subparsers.required = True
@@ -60,17 +64,73 @@ def MainParser():
return parser
-#dynamically determine all the providers available.
+# Convert returned JSON into a nice table for command line usage
+def generate_table_result(logger, output=None, without_header=None):
+ try:
+ _ = (entry for entry in output)
+ except:
+ logger.debug('Command output is not iterable, and then cannot be printed with --quiet parameter not enabled.')
+ return None
+
+ array = [[row['id'], row['type'], row['name'], row['content'], row['ttl']] for row in output]
+
+ # Insert header (insert before calculating the max width of each column to take headers size into account)
+ if not without_header:
+ headers = ['ID', 'TYPE', 'NAME', 'CONTENT', 'TTL']
+ array.insert(0, headers)
+
+ columnWidths = [0, 0, 0, 0, 0]
+ # Find max width for each column
+ for row in array:
+ for idx, col in enumerate(row):
+ width = len(str(col))
+ if width > columnWidths[idx]:
+ columnWidths[idx] = width
+
+ # Add a 'nice' separator
+ if not without_header:
+ array.insert(1, ['-' * columnWidths[idx] for idx in range(len(columnWidths))])
+
+ # Construct table to be printed
+ table = []
+ for row in array:
+ rowList = []
+ for idx, col in enumerate(row):
+ rowList.append(str(col).ljust(columnWidths[idx]))
+ table.append(' '.join(rowList))
+
+ # Return table
+ return '\n'.join(table)
+
+# Print the relevant output for given output_type
+def handle_output(results, output_type):
+ if not output_type == 'QUIET':
+ if not output_type == 'JSON':
+ table = generate_table_result(logger, results, output_type == 'TABLE-NO-HEADER')
+ if table:
+ print(table)
+ else:
+ try:
+ _ = (entry for entry in results)
+ json_str = json.dumps(results)
+ if json_str:
+ print(json_str)
+ except:
+ logger.debug('Output is not a JSON, and then cannot be printed with --output=JSON parameter.')
+ pass
+
+# Dynamically determine all the providers available.
def main():
-
parsed_args = MainParser().parse_args()
log_level = logging.getLevelName(parsed_args.log_level)
logging.basicConfig(stream=sys.stdout, level=log_level, format='%(message)s')
logger.debug('Arguments: %s', parsed_args)
- client = Client(parsed_args.__dict__)
- client.execute()
+ client = Client(vars(parsed_args))
+
+ results = client.execute()
+ handle_output(results, parsed_args.output)
if __name__ == '__main__':
main()
|
AnalogJ__lexicon-336
|
[
{
"changes": {
"added_entities": [
"lexicon/cli.py:generate_list_table_result",
"lexicon/cli.py:generate_table_results"
],
"added_modules": [
"lexicon/cli.py:generate_list_table_result",
"lexicon/cli.py:generate_table_results"
],
"edited_entities": [
"lexicon/cli.py:generate_table_result",
"lexicon/cli.py:handle_output",
"lexicon/cli.py:main"
],
"edited_modules": [
"lexicon/cli.py:generate_table_result",
"lexicon/cli.py:handle_output",
"lexicon/cli.py:main"
]
},
"file": "lexicon/cli.py"
}
] |
AnalogJ/lexicon
|
27106bded0bfa8d44ffe3f449ca2e4871588be0f
|
Memset provider: TypeError: string indices must be integers
Hi,
When using the Memset provider with the default table formatting I get this error:
```bash
$ lexicon memset create example.com TXT --name _acme-challenge.example.com --content BLAH --ttl 300
Traceback (most recent call last):
File "/usr/local/bin/lexicon", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/lexicon/__main__.py", line 133, in main
handle_output(results, parsed_args.output)
File "/usr/local/lib/python2.7/dist-packages/lexicon/__main__.py", line 109, in handle_output
table = generate_table_result(logger, results, output_type == 'TABLE-NO-HEADER')
File "/usr/local/lib/python2.7/dist-packages/lexicon/__main__.py", line 75, in generate_table_result
array = [[row['id'], row['type'], row['name'], row['content'], row['ttl']] for row in output]
TypeError: string indices must be integers
```
I think this is because `output` is a string not an array - when I added `print output` I got a string like `969f9caabe19859c11249333dd80aa15`.
When I use `--output JSON` I get the same ID plus quotes:
```bash
$ lexicon memset create example.com TXT --name _acme-challenge.example.com --content BLAH --ttl 300 --output JSON
"969f9caabe19859c11249333dd80aa15"
```
I know Memset's not public so if you need any help to test it just let me know. For now I'll work around it with `--output QUIET` since I don't really care about the output here.
Thanks!
Dave
|
diff --git a/lexicon/cli.py b/lexicon/cli.py
index dbef1ae2..0b5425ce 100644
--- a/lexicon/cli.py
+++ b/lexicon/cli.py
@@ -14,12 +14,10 @@ from lexicon.parser import generate_cli_main_parser
logger = logging.getLogger(__name__) # pylint: disable=C0103
-def generate_table_result(lexicon_logger, output=None, without_header=None):
- """Convert returned JSON into a nice table for command line usage"""
- try:
- _ = (entry for entry in output)
- except TypeError:
- lexicon_logger.debug('Command output is not iterable, and then cannot '
+def generate_list_table_result(lexicon_logger, output=None, without_header=None):
+ """Convert returned data from list actions into a nice table for command line usage"""
+ if not isinstance(output, list):
+ lexicon_logger.debug('Command output is not a list, and then cannot '
'be printed with --quiet parameter not enabled.')
return None
@@ -58,26 +56,43 @@ def generate_table_result(lexicon_logger, output=None, without_header=None):
table.append(' '.join(row_list))
# Return table
- return '\n'.join(table)
+ return os.linesep.join(table)
-def handle_output(results, output_type):
+def generate_table_results(output=None, without_header=None):
+ """Convert returned data from non-list actions into a nice table for command line usage"""
+ array = []
+ str_output = str(output)
+
+ if not without_header:
+ array.append('RESULT')
+ array.append('-' * max(6, len(str_output)))
+
+ array.append(str_output)
+ return os.linesep.join(array)
+
+
+def handle_output(results, output_type, action):
"""Print the relevant output for given output_type"""
- if not output_type == 'QUIET':
- if not output_type == 'JSON':
- table = generate_table_result(
+ if output_type == 'QUIET':
+ return
+
+ if not output_type == 'JSON':
+ if action == 'list':
+ table = generate_list_table_result(
logger, results, output_type == 'TABLE-NO-HEADER')
- if table:
- print(table)
else:
- try:
- _ = (entry for entry in results)
- json_str = json.dumps(results)
- if json_str:
- print(json_str)
- except TypeError:
- logger.debug('Output is not a JSON, and then cannot '
- 'be printed with --output=JSON parameter.')
+ table = generate_table_results(results, output_type == 'TABLE-NO-HEADER')
+ if table:
+ print(table)
+ else:
+ try:
+ json_str = json.dumps(results)
+ if json_str:
+ print(json_str)
+ except TypeError:
+ logger.debug('Output is not JSON serializable, and then cannot '
+ 'be printed with --output=JSON parameter.')
def main():
@@ -101,7 +116,7 @@ def main():
results = client.execute()
- handle_output(results, parsed_args.output)
+ handle_output(results, parsed_args.output, config.resolve('lexicon:action'))
if __name__ == '__main__':
|
AngryMaciek__angry-moran-simulator-24
|
[
{
"changes": {
"added_entities": [
"moranpycess/MoranProcess.py:MoranProcess.PlotSize",
"moranpycess/MoranProcess.py:MoranProcess.PlotAvgBirthPayoff",
"moranpycess/MoranProcess.py:MoranProcess.PlotAvgDeathPayoff",
"moranpycess/MoranProcess.py:MoranProcess.PlotBirthFitness",
"moranpycess/MoranProcess.py:MoranProcess.PlotDeathFitness",
"moranpycess/MoranProcess.py:MoranProcess.PlotEntropy"
],
"added_modules": null,
"edited_entities": [
"moranpycess/MoranProcess.py:PlotSize",
"moranpycess/MoranProcess.py:PlotAvgBirthPayoff",
"moranpycess/MoranProcess.py:PlotAvgDeathPayoff",
"moranpycess/MoranProcess.py:PlotBirthFitness",
"moranpycess/MoranProcess.py:PlotDeathFitness",
"moranpycess/MoranProcess.py:PlotEntropy"
],
"edited_modules": [
"moranpycess/MoranProcess.py:PlotSize",
"moranpycess/MoranProcess.py:PlotAvgBirthPayoff",
"moranpycess/MoranProcess.py:PlotAvgDeathPayoff",
"moranpycess/MoranProcess.py:PlotBirthFitness",
"moranpycess/MoranProcess.py:PlotDeathFitness",
"moranpycess/MoranProcess.py:PlotEntropy",
"moranpycess/MoranProcess.py:MoranProcess"
]
},
"file": "moranpycess/MoranProcess.py"
},
{
"changes": {
"added_entities": [
"moranpycess/MoranProcess2D.py:MoranProcess2D.PlotSize2D",
"moranpycess/MoranProcess2D.py:MoranProcess2D.PlotEntropy2D",
"moranpycess/MoranProcess2D.py:MoranProcess2D.PlotPopulationSnapshot2D"
],
"added_modules": null,
"edited_entities": [
"moranpycess/MoranProcess2D.py:PlotSize2D",
"moranpycess/MoranProcess2D.py:PlotEntropy2D",
"moranpycess/MoranProcess2D.py:PlotPopulationSnapshot2D"
],
"edited_modules": [
"moranpycess/MoranProcess2D.py:PlotSize2D",
"moranpycess/MoranProcess2D.py:PlotEntropy2D",
"moranpycess/MoranProcess2D.py:PlotPopulationSnapshot2D",
"moranpycess/MoranProcess2D.py:MoranProcess2D"
]
},
"file": "moranpycess/MoranProcess2D.py"
},
{
"changes": {
"added_entities": [
"moranpycess/MoranProcess3D.py:MoranProcess3D.PlotSize3D",
"moranpycess/MoranProcess3D.py:MoranProcess3D.PlotEntropy3D"
],
"added_modules": null,
"edited_entities": [
"moranpycess/MoranProcess3D.py:PlotSize3D",
"moranpycess/MoranProcess3D.py:PlotEntropy3D"
],
"edited_modules": [
"moranpycess/MoranProcess3D.py:PlotSize3D",
"moranpycess/MoranProcess3D.py:PlotEntropy3D",
"moranpycess/MoranProcess3D.py:MoranProcess3D"
]
},
"file": "moranpycess/MoranProcess3D.py"
},
{
"changes": {
"added_entities": null,
"added_modules": null,
"edited_entities": null,
"edited_modules": null
},
"file": "moranpycess/__init__.py"
}
] |
AngryMaciek/angry-moran-simulator
|
a065091015628bd568f9168b3abf3d8c84167be7
|
Python modularisation
double-check the modularisation setup in the `init`.
|
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index fbc60d7..db7d90e 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -51,7 +51,7 @@ jobs:
run: |
flake8 --max-line-length=88 --ignore F401 moranpycess/__init__.py
flake8 --max-line-length=88 moranpycess/Individual.py
- flake8 --max-line-length=95 --ignore F401,E231,W503,E741 moranpycess/MoranProcess.py
+ flake8 --max-line-length=101 --ignore F401,E231,W503,E741 moranpycess/MoranProcess.py
flake8 --max-line-length=101 --ignore F401,E231,W503,E741 moranpycess/MoranProcess2D.py
flake8 --max-line-length=101 --ignore F401,E231,W503,E741 moranpycess/MoranProcess3D.py
flake8 --max-line-length=88 --ignore F401,E402 tests/unit/context.py
diff --git a/documentation.md b/documentation.md
index 4426052..e48d0aa 100644
--- a/documentation.md
+++ b/documentation.md
@@ -77,7 +77,7 @@ ## General Moran Process
* per-sub-population Death Fitness of an individual from a given sub-popualtion
* Entropy of the distribution of Strategies in the whole population
-Additionally to the *MoranProcess* class the user is equipped with several plotting functions to visualise results of the simulation:
+The *MoranProcess* class is equipped with several plotting methods to visualise results of the simulation:
* `PlotSize`
* `PlotAvgBirthPayoff`
* `PlotAvgDeathPayoff`
@@ -87,13 +87,11 @@ ## General Moran Process
Each of which with the same signature:
```python
-def FUNCTION(mp, df, path):
+def FUNCTION(self, df, path):
```
With the following arguments:
```python
-mp # instance of the MoranProcess
-
df # simulation results - pandas dataframe returned by the method .simulate()
path # path for the output plot in png format
@@ -101,12 +99,12 @@ ## General Moran Process
Following the previous simulation one may generate the plots with:
```python
-moranpycess.PlotSize(mp, df, "Size.png")
-moranpycess.PlotAvgBirthPayoff(mp, df, "AvgBirthPayoff.png")
-moranpycess.PlotAvgDeathPayoff(mp, df, "AvgDeathPayoff.png")
-moranpycess.PlotBirthFitness(mp, df, "BirthFitness.png")
-moranpycess.PlotDeathFitness(mp, df, "DeathFitness.png")
-moranpycess.PlotEntropy(mp, df, "Entropy.png")
+mp.PlotSize(df, "Size.png")
+mp.PlotAvgBirthPayoff(df, "AvgBirthPayoff.png")
+mp.PlotAvgDeathPayoff(df, "AvgDeathPayoff.png")
+mp.PlotBirthFitness(df, "BirthFitness.png")
+mp.PlotDeathFitness(df, "DeathFitness.png")
+mp.PlotEntropy(df, "Entropy.png")
```
## Moran Model based on 2D neighbourhood
@@ -172,28 +170,26 @@ ## Moran Model based on 2D neighbourhood
* per-sub-population sub-population's size
* Entropy of the distribution of Strategies in the whole population
-Additionally to the *MoranProcess2D* class the user is equipped with three plotting functions to visualise results of the simulation:
+The *MoranProcess2D* class is equipped with three plotting methods to visualise results of the simulation:
* `PlotSize2D`
* `PlotEntropy2D`
* `PlotPopulationSnapshot2D`
With `PlotSize2D` and `PlotEntropy2D` having the same signatures as their previous analogues. The latter, `PlotPopulationSnapshot2D`, may produce a heatmap-like snapshot of a population at it's current state:
```python
-def PlotPopulationSnapshot2D(mp, path):
+def PlotPopulationSnapshot2D(self, path):
```
With the following arguments:
```python
-mp # instance of the MoranProcess
-
path # path for the output plot in png format
```
Following the previous simulation one may generate the plots with:
```python
-moranpycess.PlotSize2D(mp, df, "Size2D.png")
-moranpycess.PlotEntropy2D(mp, df, "Entropy2D.png")
-moranpycess.PlotPopulationSnapshot2D(mp, "PopulationSnapshot2D.png")
+mp.PlotSize2D(df, "Size2D.png")
+mp.PlotEntropy2D(df, "Entropy2D.png")
+mp.PlotPopulationSnapshot2D("PopulationSnapshot2D.png")
```
## Moran Model based on 3D neighbourhood
@@ -255,15 +251,15 @@ ## Moran Model based on 3D neighbourhood
* per-sub-population sub-population's size
* Entropy of the distribution of Strategies in the whole population
-Additionally to the *MoranProcess3D* class the user is equipped with two plotting functions to visualise results of the simulation:
+The *MoranProcess3D* class is equipped with two plotting methods to visualise results of the simulation:
* `PlotSize3D`
* `PlotEntropy3D`
The functions have the same signatures as their previous analogues.
Following the previous simulation one may generate the plots with:
```python
-moranpycess.PlotSize3D(mp, df, "Size3D.png")
-moranpycess.PlotEntropy3D(mp, df, "Entropy3D.png")
+mp.PlotSize3D(df, "Size3D.png")
+mp.PlotEntropy3D(df, "Entropy3D.png")
```
## Use cases
diff --git a/moranpycess/MoranProcess.py b/moranpycess/MoranProcess.py
index 57e5f68..6e96db2 100644
--- a/moranpycess/MoranProcess.py
+++ b/moranpycess/MoranProcess.py
@@ -425,114 +425,108 @@ def UpdateEntropy(self):
if fraction != 0.0:
self.Entropy -= fraction * np.log2(fraction)
-
-def PlotSize(mp, df, path):
- """Plot the sub-populations' sizes after a simulation of a given Moran Process."""
- plt.figure(figsize=(14, 6))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- cmap = plt.get_cmap("coolwarm")
- columns = [l + "__size" for l in mp.init_label_list]
- df_copy = df[columns].copy()
- df_copy.columns = mp.init_label_list
- df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
- population_size = len(mp.population)
- ax.set_ylim([0, population_size])
- plt.xlabel("Generation", size=14)
- plt.ylabel("# Individuals", size=14)
- ax.tick_params(axis="both", which="major", labelsize=12)
- ax.legend(loc=4, fontsize=20)
- plt.savefig(fname=path, dpi=300)
-
-
-def PlotAvgBirthPayoff(mp, df, path):
- """Plot the sub-populations' AvgBirthPayoff after a simulation of a given Moran Process."""
- plt.figure(figsize=(14, 6))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- cmap = plt.get_cmap("coolwarm")
- columns = [l + "__AvgBirthPayoff" for l in mp.init_label_list]
- df_copy = df[columns].copy()
- df_copy.columns = mp.init_label_list
- df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
- plt.xlabel("Generation", size=14)
- plt.ylabel("Average Birth Payoff", size=14)
- ax.tick_params(axis="both", which="major", labelsize=12)
- ax.legend(loc=4, fontsize=20)
- plt.savefig(fname=path, dpi=300)
-
-
-def PlotAvgDeathPayoff(mp, df, path):
- """Plot the sub-populations' AvgDeathPayoff after a simulation of a given Moran Process."""
- plt.figure(figsize=(14, 6))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- cmap = plt.get_cmap("coolwarm")
- columns = [l + "__AvgDeathPayoff" for l in mp.init_label_list]
- df_copy = df[columns].copy()
- df_copy.columns = mp.init_label_list
- df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
- plt.xlabel("Generation", size=14)
- plt.ylabel("Average Death Payoff", size=14)
- ax.tick_params(axis="both", which="major", labelsize=12)
- ax.legend(loc=4, fontsize=20)
- plt.savefig(fname=path, dpi=300)
-
-
-def PlotBirthFitness(mp, df, path):
- """Plot the sub-populations' BirthFitness after a simulation of a given Moran Process."""
- plt.figure(figsize=(14, 6))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- cmap = plt.get_cmap("coolwarm")
- columns = [l + "__BirthFitness" for l in mp.init_label_list]
- df_copy = df[columns].copy()
- df_copy.columns = mp.init_label_list
- df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
- plt.xlabel("Generation", size=14)
- plt.ylabel("Birth Fitness", size=14)
- ax.tick_params(axis="both", which="major", labelsize=12)
- ax.legend(loc=4, fontsize=20)
- plt.savefig(fname=path, dpi=300)
-
-
-def PlotDeathFitness(mp, df, path):
- """Plot the sub-populations' DeathFitness after a simulation of a given Moran Process."""
- plt.figure(figsize=(14, 6))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- cmap = plt.get_cmap("coolwarm")
- columns = [l + "__DeathFitness" for l in mp.init_label_list]
- df_copy = df[columns].copy()
- df_copy.columns = mp.init_label_list
- df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
- plt.xlabel("Generation", size=14)
- plt.ylabel("Death Fitness", size=14)
- ax.tick_params(axis="both", which="major", labelsize=12)
- ax.legend(loc=4, fontsize=20)
- plt.savefig(fname=path, dpi=300)
-
-
-def PlotEntropy(mp, df, path):
- """Plot the whole populations entropy after a simulation of a given Moran Process."""
- plt.figure(figsize=(14, 6))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- df["Entropy"].plot(color="black", linewidth=1.5, ax=ax, label="Entropy")
- plt.xlabel("Generation", size=14)
- plt.ylabel("", size=14)
- ax.tick_params(axis="both", which="major", labelsize=12)
- ax.legend(loc=4, fontsize=20)
- plt.savefig(fname=path, dpi=300)
+ def PlotSize(self, df, path):
+ """Plot the sub-populations' sizes after a simulation of a given Moran Process."""
+ plt.figure(figsize=(14, 6))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ cmap = plt.get_cmap("coolwarm")
+ columns = [l + "__size" for l in self.init_label_list]
+ df_copy = df[columns].copy()
+ df_copy.columns = self.init_label_list
+ df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
+ population_size = len(self.population)
+ ax.set_ylim([0, population_size])
+ plt.xlabel("Generation", size=14)
+ plt.ylabel("# Individuals", size=14)
+ ax.tick_params(axis="both", which="major", labelsize=12)
+ ax.legend(loc=4, fontsize=20)
+ plt.savefig(fname=path, dpi=300)
+
+ def PlotAvgBirthPayoff(self, df, path):
+ """Plot the sub-populations' AvgBirthPayoff after a simulation of a given Moran Process."""
+ plt.figure(figsize=(14, 6))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ cmap = plt.get_cmap("coolwarm")
+ columns = [l + "__AvgBirthPayoff" for l in self.init_label_list]
+ df_copy = df[columns].copy()
+ df_copy.columns = self.init_label_list
+ df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
+ plt.xlabel("Generation", size=14)
+ plt.ylabel("Average Birth Payoff", size=14)
+ ax.tick_params(axis="both", which="major", labelsize=12)
+ ax.legend(loc=4, fontsize=20)
+ plt.savefig(fname=path, dpi=300)
+
+ def PlotAvgDeathPayoff(self, df, path):
+ """Plot the sub-populations' AvgDeathPayoff after a simulation of a given Moran Process."""
+ plt.figure(figsize=(14, 6))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ cmap = plt.get_cmap("coolwarm")
+ columns = [l + "__AvgDeathPayoff" for l in self.init_label_list]
+ df_copy = df[columns].copy()
+ df_copy.columns = self.init_label_list
+ df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
+ plt.xlabel("Generation", size=14)
+ plt.ylabel("Average Death Payoff", size=14)
+ ax.tick_params(axis="both", which="major", labelsize=12)
+ ax.legend(loc=4, fontsize=20)
+ plt.savefig(fname=path, dpi=300)
+
+ def PlotBirthFitness(self, df, path):
+ """Plot the sub-populations' BirthFitness after a simulation of a given Moran Process."""
+ plt.figure(figsize=(14, 6))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ cmap = plt.get_cmap("coolwarm")
+ columns = [l + "__BirthFitness" for l in self.init_label_list]
+ df_copy = df[columns].copy()
+ df_copy.columns = self.init_label_list
+ df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
+ plt.xlabel("Generation", size=14)
+ plt.ylabel("Birth Fitness", size=14)
+ ax.tick_params(axis="both", which="major", labelsize=12)
+ ax.legend(loc=4, fontsize=20)
+ plt.savefig(fname=path, dpi=300)
+
+ def PlotDeathFitness(self, df, path):
+ """Plot the sub-populations' DeathFitness after a simulation of a given Moran Process."""
+ plt.figure(figsize=(14, 6))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ cmap = plt.get_cmap("coolwarm")
+ columns = [l + "__DeathFitness" for l in self.init_label_list]
+ df_copy = df[columns].copy()
+ df_copy.columns = self.init_label_list
+ df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
+ plt.xlabel("Generation", size=14)
+ plt.ylabel("Death Fitness", size=14)
+ ax.tick_params(axis="both", which="major", labelsize=12)
+ ax.legend(loc=4, fontsize=20)
+ plt.savefig(fname=path, dpi=300)
+
+ def PlotEntropy(self, df, path):
+ """Plot the whole populations entropy after a simulation of a given Moran Process."""
+ plt.figure(figsize=(14, 6))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ df["Entropy"].plot(color="black", linewidth=1.5, ax=ax, label="Entropy")
+ plt.xlabel("Generation", size=14)
+ plt.ylabel("", size=14)
+ ax.tick_params(axis="both", which="major", labelsize=12)
+ ax.legend(loc=4, fontsize=20)
+ plt.savefig(fname=path, dpi=300)
diff --git a/moranpycess/MoranProcess2D.py b/moranpycess/MoranProcess2D.py
index 8cda90d..6012f53 100644
--- a/moranpycess/MoranProcess2D.py
+++ b/moranpycess/MoranProcess2D.py
@@ -476,68 +476,68 @@ def simulate(self, generations):
return log_df
-
-def PlotSize2D(mp, df, path):
- """Plot the sub-populations' sizes after a simulation of a given 2D Moran Process."""
- plt.figure(figsize=(14, 6))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- cmap = plt.get_cmap("coolwarm")
- columns = [l + "__size" for l in mp.init_label_list]
- df_copy = df[columns].copy()
- df_copy.columns = mp.init_label_list
- df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
- population_size = mp.population.size
- ax.set_ylim([0, population_size])
- plt.xlabel("Generation", size=14)
- plt.ylabel("# Individuals", size=14)
- ax.tick_params(axis="both", which="major", labelsize=12)
- ax.legend(loc=4, fontsize=20)
- plt.savefig(fname=path, dpi=300)
-
-
-def PlotEntropy2D(mp, df, path):
- """Plot the whole populations entropy after a simulation of a given 2D Moran Process."""
- plt.figure(figsize=(14, 6))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- df["Entropy"].plot(color="black", linewidth=1.5, ax=ax, label="Entropy")
- plt.xlabel("Generation", size=14)
- plt.ylabel("", size=14)
- ax.tick_params(axis="both", which="major", labelsize=12)
- ax.legend(loc=4, fontsize=20)
- plt.savefig(fname=path, dpi=300)
-
-
-def PlotPopulationSnapshot2D(mp, path):
- """Plot the whole populations entropy after a simulation of a given 2D Moran Process."""
- plt.figure(figsize=(10, 10))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- plot_grid = mp.curr_grid.copy()
- ticks_labels = []
- for label_index in range(len(mp.init_label_list)):
- plot_grid[plot_grid == mp.init_label_list[label_index]] = label_index
- ticks_labels.append(mp.init_label_list[label_index])
- plot_grid = plot_grid.astype(float)
- cmap = plt.get_cmap(
- "coolwarm", np.max(plot_grid) - np.min(plot_grid) + 1
- ) # get discrete colormap
- mat = plt.matshow(
- plot_grid, cmap=cmap, vmin=np.min(plot_grid) - 0.5, vmax=np.max(plot_grid) + 0.5
- ) # set limits .5 outside true range
- cax = plt.colorbar(
- mat, ticks=np.arange(np.min(plot_grid), np.max(plot_grid) + 1)
- ) # tell the colorbar to tick at integers
- cax.set_ticklabels(ticks_labels)
- plt.ylabel("")
- plt.yticks([])
- plt.xlabel("")
- plt.xticks([])
- plt.savefig(fname=path, dpi=300)
+ def PlotSize2D(self, df, path):
+ """Plot the sub-populations' sizes after a simulation of a given 2D Moran Process."""
+ plt.figure(figsize=(14, 6))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ cmap = plt.get_cmap("coolwarm")
+ columns = [l + "__size" for l in self.init_label_list]
+ df_copy = df[columns].copy()
+ df_copy.columns = self.init_label_list
+ df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
+ population_size = self.population.size
+ ax.set_ylim([0, population_size])
+ plt.xlabel("Generation", size=14)
+ plt.ylabel("# Individuals", size=14)
+ ax.tick_params(axis="both", which="major", labelsize=12)
+ ax.legend(loc=4, fontsize=20)
+ plt.savefig(fname=path, dpi=300)
+
+ def PlotEntropy2D(self, df, path):
+ """Plot the whole populations entropy after a simulation of a given 2D Moran Process."""
+ plt.figure(figsize=(14, 6))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ df["Entropy"].plot(color="black", linewidth=1.5, ax=ax, label="Entropy")
+ plt.xlabel("Generation", size=14)
+ plt.ylabel("", size=14)
+ ax.tick_params(axis="both", which="major", labelsize=12)
+ ax.legend(loc=4, fontsize=20)
+ plt.savefig(fname=path, dpi=300)
+
+ def PlotPopulationSnapshot2D(self, path):
+ """Plot the whole populations entropy after a simulation of a given 2D Moran Process."""
+ plt.figure(figsize=(10, 10))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ plot_grid = self.curr_grid.copy()
+ ticks_labels = []
+ for label_index in range(len(self.init_label_list)):
+ plot_grid[plot_grid == self.init_label_list[label_index]] = label_index
+ ticks_labels.append(self.init_label_list[label_index])
+ plot_grid = plot_grid.astype(float)
+ cmap = plt.get_cmap(
+ "coolwarm", np.max(plot_grid) - np.min(plot_grid) + 1
+ ) # get discrete colormap
+ mat = plt.matshow(
+ plot_grid,
+ cmap=cmap,
+ vmin=np.min(plot_grid) - 0.5,
+ vmax=np.max(plot_grid) + 0.5,
+ ) # set limits .5 outside true range
+ cax = plt.colorbar(
+ mat, ticks=np.arange(np.min(plot_grid), np.max(plot_grid) + 1)
+ ) # tell the colorbar to tick at integers
+ cax.set_ticklabels(ticks_labels)
+ plt.ylabel("")
+ plt.yticks([])
+ plt.xlabel("")
+ plt.xticks([])
+ plt.savefig(fname=path, dpi=300)
diff --git a/moranpycess/MoranProcess3D.py b/moranpycess/MoranProcess3D.py
index 8754103..2036c52 100644
--- a/moranpycess/MoranProcess3D.py
+++ b/moranpycess/MoranProcess3D.py
@@ -591,38 +591,36 @@ def simulate(self, generations):
return log_df
-
-def PlotSize3D(mp, df, path):
- """Plot the sub-populations' sizes after a simulation of a given 3D Moran Process."""
- plt.figure(figsize=(14, 6))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- cmap = plt.get_cmap("coolwarm")
- columns = [l + "__size" for l in mp.init_label_list]
- df_copy = df[columns].copy()
- df_copy.columns = mp.init_label_list
- df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
- population_size = mp.population.size
- ax.set_ylim([0, population_size])
- plt.xlabel("Generation", size=14)
- plt.ylabel("# Individuals", size=14)
- ax.tick_params(axis="both", which="major", labelsize=12)
- ax.legend(loc=4, fontsize=20)
- plt.savefig(fname=path, dpi=300)
-
-
-def PlotEntropy3D(mp, df, path):
- """Plot the whole populations entropy after a simulation of a given 3D Moran Process."""
- plt.figure(figsize=(14, 6))
- ax = plt.gca()
- ax.tick_params(width=1)
- for axis in ["top", "bottom", "left", "right"]:
- ax.spines[axis].set_linewidth(1)
- df["Entropy"].plot(color="black", linewidth=1.5, ax=ax, label="Entropy")
- plt.xlabel("Generation", size=14)
- plt.ylabel("", size=14)
- ax.tick_params(axis="both", which="major", labelsize=12)
- ax.legend(loc=4, fontsize=20)
- plt.savefig(fname=path, dpi=300)
+ def PlotSize3D(self, df, path):
+ """Plot the sub-populations' sizes after a simulation of a given 3D Moran Process."""
+ plt.figure(figsize=(14, 6))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ cmap = plt.get_cmap("coolwarm")
+ columns = [l + "__size" for l in self.init_label_list]
+ df_copy = df[columns].copy()
+ df_copy.columns = self.init_label_list
+ df_copy.plot(linewidth=1.5, ax=ax, cmap=cmap)
+ population_size = self.population.size
+ ax.set_ylim([0, population_size])
+ plt.xlabel("Generation", size=14)
+ plt.ylabel("# Individuals", size=14)
+ ax.tick_params(axis="both", which="major", labelsize=12)
+ ax.legend(loc=4, fontsize=20)
+ plt.savefig(fname=path, dpi=300)
+
+ def PlotEntropy3D(self, df, path):
+ """Plot the whole populations entropy after a simulation of a given 3D Moran Process."""
+ plt.figure(figsize=(14, 6))
+ ax = plt.gca()
+ ax.tick_params(width=1)
+ for axis in ["top", "bottom", "left", "right"]:
+ ax.spines[axis].set_linewidth(1)
+ df["Entropy"].plot(color="black", linewidth=1.5, ax=ax, label="Entropy")
+ plt.xlabel("Generation", size=14)
+ plt.ylabel("", size=14)
+ ax.tick_params(axis="both", which="major", labelsize=12)
+ ax.legend(loc=4, fontsize=20)
+ plt.savefig(fname=path, dpi=300)
diff --git a/moranpycess/__init__.py b/moranpycess/__init__.py
index 05705e5..a1dcf59 100644
--- a/moranpycess/__init__.py
+++ b/moranpycess/__init__.py
@@ -16,11 +16,5 @@
# imports
from .Individual import Individual
from .MoranProcess import MoranProcess
-from .MoranProcess import PlotSize
-from .MoranProcess import PlotAvgBirthPayoff, PlotAvgDeathPayoff
-from .MoranProcess import PlotBirthFitness, PlotDeathFitness
-from .MoranProcess import PlotEntropy
from .MoranProcess2D import MoranProcess2D
-from .MoranProcess2D import PlotSize2D, PlotEntropy2D, PlotPopulationSnapshot2D
from .MoranProcess3D import MoranProcess3D
-from .MoranProcess3D import PlotSize3D, PlotEntropy3D
|
ApptuitAI__apptuit-py-10
|
[
{
"changes": {
"added_entities": [
"apptuit/apptuit_client.py:DataPoint.value"
],
"added_modules": null,
"edited_entities": null,
"edited_modules": [
"apptuit/apptuit_client.py:DataPoint"
]
},
"file": "apptuit/apptuit_client.py"
}
] |
ApptuitAI/apptuit-py
|
65d256693243562917c4dfd0e8a753781b153b36
|
DataPoint should validate parameters
Right now DataPoint does not validate if the "value" parameter is int/long or float. Eventual API call fails if the value is a string (even representation of int/float).
DataPoint should perform client side validation of all input parameters (metricname, tags, values) without waiting for an error from the server.
As a bonus, if the value is a string representation of int/float, we could coerce it into a number instead of erroring out.
|
diff --git a/apptuit/apptuit_client.py b/apptuit/apptuit_client.py
index afa6792..2049aa9 100644
--- a/apptuit/apptuit_client.py
+++ b/apptuit/apptuit_client.py
@@ -286,6 +286,23 @@ class DataPoint(object):
raise ValueError("Tag value %s contains an invalid character, allowed characters are a-z, A-Z, 0-9, -, _, ., and /" % tagv)
self._tags = tags
+ @property
+ def value(self):
+ return self._value
+
+ @value.setter
+ def value(self, value):
+ if isinstance(value, (int, float)):
+ self._value = value
+
+ elif isinstance(value, str):
+ try:
+ self._value = float(value)
+ except ValueError:
+ raise ValueError("Expected a numeric value got %s" % value)
+ else:
+ raise ValueError("Expected a numeric value for the value parameter")
+
def __repr__(self):
repr = self.metric + "{"
for tagk, tagv in self.tags.items():
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.