Beispiel #1
0
 def test_interger_sequence_datetime_different_duration(self):
     converter = IntegerSequenceDateTimeConvertSpec("2019-01-01T00:00", 0,
                                                    "2h")
     self.assertEqual(converter.convert_function()("t00000"),
                      DateTime("2019-01-01T00:00"))
     self.assertEqual(converter.convert_function()("t00002"),
                      DateTime("2019-01-01T04:00"))
Beispiel #2
0
 def test_interger_sequence_datetime_shifted_start_int(self):
     converter = IntegerSequenceDateTimeConvertSpec("2019-01-01T00:00", 1,
                                                    "1h")
     self.assertEqual(converter.convert_function()("t00000"),
                      DateTime("2018-12-31T23:00"))
     self.assertEqual(converter.convert_function()("t00002"),
                      DateTime("2019-01-01T01:00"))
 def test_convert_leaf_maps(self):
     nested_map = Map(
         [DateTime("2020-07-03 12:00:00"),
          DateTime("2020-07-03 12:00:00")], [22.2, 23.3])
     map_ = Map([1.0], [nested_map])
     model = MapModel(map_)
     model.convert_leaf_maps()
     self.assertEqual(model.columnCount(), 3)
     self.assertEqual(model.rowCount(), 2)
     self.assertEqual(model.index(0, 0).data(), 1.0)
     self.assertEqual(model.index(0, 1).data(), "Time series")
     self.assertEqual(model.index(0, 2).data(), "")
     self.assertEqual(model.index(1, 0).data(), "")
     self.assertEqual(model.index(1, 1).data(), "")
     self.assertEqual(model.index(1, 2).data(), "")
 def get_spec(self):
     start_datetime = DateTime(self.datetime.dateTime().toString(
         Qt.ISODate))
     duration = Duration(self.duration.text())
     start_int = self.start_integer.value()
     return IntegerSequenceDateTimeConvertSpec(start_datetime, start_int,
                                               duration)
 def convert(value):
     try:
         int_str = pattern.search(str(value)).group()
         int_value = int(int_str) - start_int
         return DateTime(start_datetime + int_value * duration)
     except (ValueError, ParameterValueFormatError):
         raise ValueError(f"Could not convert '{value}' to a DateTime")
 def __init__(self, start_datetime, start_int, duration):
     if not isinstance(start_datetime, DateTime):
         start_datetime = DateTime(start_datetime)
     if not isinstance(duration, Duration):
         duration = Duration(duration)
     self.start_datetime = start_datetime
     self.start_int = start_int
     self.duration = duration
Beispiel #7
0
    def __init__(self, parent=None):
        from ..ui.datetime_editor import Ui_DatetimeEditor

        super().__init__(parent)
        self._value = DateTime("2000-01-01")
        self._ui = Ui_DatetimeEditor()
        self._ui.setupUi(self)
        self._ui.datetime_edit.setMinimumDate(QDate(1, 1, 1))
        self._ui.datetime_edit.setDateTime(_datetime_to_QDateTime(self._value.value))
        self._ui.datetime_edit.dateTimeChanged.connect(self._change_datetime)
Beispiel #8
0
    def _read_pasted_text(text):
        """
        Parses a given CSV table

        Args:
            text (str): a CSV table
        Returns:
            list of list: a list of table rows
        """
        data = list()
        with io.StringIO(text) as input_stream:
            reader = csv.reader(input_stream, delimiter='\t')
            for row in reader:
                data_row = list()
                for cell in row:
                    try:
                        number = locale.atof(cell)
                        data_row.append(number)
                        continue
                    except ValueError:
                        pass
                    try:
                        # Try parsing Duration before DateTime because DateTime will happily accept strings like '1h'
                        value = Duration(cell)
                        data_row.append(value)
                        continue
                    except SpineDBAPIError:
                        pass
                    try:
                        value = DateTime(cell)
                        data_row.append(value)
                        continue
                    except SpineDBAPIError:
                        pass
                    try:
                        value = from_database(cell)
                        data_row.append(value)
                        continue
                    except ParameterValueFormatError:
                        pass
                    data_row.append(cell)
                data.append(data_row)
        return data
def value_to_convert_spec(value):
    if isinstance(value, ConvertSpec):
        return value
    if isinstance(value, str):
        spec = {
            "datetime": DateTimeConvertSpec,
            "duration": DurationConvertSpec,
            "float": FloatConvertSpec,
            "string": StringConvertSpec,
        }.get(value)
        return spec()
    if isinstance(value, dict):
        start_datetime = DateTime(value.get("start_datetime"))
        duration = Duration(value.get("duration"))
        start_int = value.get("start_int")
        return IntegerSequenceDateTimeConvertSpec(start_datetime, start_int,
                                                  duration)
    raise TypeError(
        f"value must be str or dict instead got {type(value).__name__}")
Beispiel #10
0
 def _change_datetime(self, new_datetime):
     """Updates the internal DateTime value"""
     new_value = DateTime(_QDateTime_to_datetime(new_datetime))
     self._value = new_value
 def test_editor_sets_datetime_in_parent_model(self):
     time_stamp = DateTime(dateutil.parser.parse('2019-07-03T12:00'))
     self._check_parent_model_updated_when_closed(time_stamp)
Beispiel #12
0
 def test_DateTime(self):
     self.assertEqual(
         DateTimeConvertSpec().convert_function()("2019-01-01T00:00"),
         DateTime("2019-01-01T00:00"))
Beispiel #13
0
 def test_date_time_in_tool_tip_role(self):
     value = DateTime("2019-07-12T16:00")
     self.db_mngr.get_item.return_value = {"value": to_database(value)}
     self.assertIsNone(self.get_value(Qt.ToolTipRole))
Beispiel #14
0
 def test_date_time_in_edit_role(self):
     value = DateTime("2019-07-12T16:00")
     self.db_mngr.get_item.return_value = {"value": to_database(value)}
     formatted = self.get_value(Qt.EditRole)
     self.assertEqual(formatted, to_database(value))
 def test_initial_value(self):
     editor = DatetimeEditor()
     value = editor.value()
     self.assertEqual(value, DateTime("2000-01-01T00:00:00"))
 def test_value_access(self):
     editor = DatetimeEditor()
     editor.set_value(DateTime("2000-02-02T20:02"))
     self.assertEqual(editor.value(), DateTime("2000-02-02T20:02"))
Beispiel #17
0
def _make_pivot_proxy_model():
    """Returns a prefilled PivotTableModel."""
    db_mngr = MagicMock()
    db_mngr.get_value.side_effect = lambda db_map, item_type, id_, role: from_database(
        id_)
    mock_db_map = MagicMock()
    mock_db_map.codename = "codename"
    db_mngr.undo_action.__getitem__.side_effect = lambda key: QAction()
    db_mngr.redo_action.__getitem__.side_effect = lambda key: QAction()
    with patch.object(SpineDBEditor,
                      "restore_ui"), patch.object(SpineDBEditor, "show"):
        spine_db_editor = SpineDBEditor(db_mngr, mock_db_map)
    spine_db_editor.create_header_widget = lambda *args, **kwargs: None
    simple_map = Map(["a", "b"], [-1.1, -2.2])
    nested_map = Map(
        ["a", "b"],
        [
            Map([DateTime("2020-11-13T11:00"),
                 DateTime("2020-11-13T12:00")], [-1.1, -2.2]),
            Map([DateTime("2020-11-13T11:00"),
                 DateTime("2020-11-13T12:00")], [-3.3, -4.4]),
        ],
    )
    nested_map_with_time_series = Map(
        ["a", "b"],
        [
            Map(
                [DateTime("2020-11-13T11:00"),
                 DateTime("2020-11-13T12:00")],
                [
                    TimeSeriesVariableResolution(
                        ["2020-11-13T11:00", "2020-11-13T12:00"], [-1.1, -2.2],
                        False, False),
                    TimeSeriesVariableResolution(
                        ["2020-11-13T12:00", "2020-11-13T13:00"], [-3.3, -4.4],
                        False, False),
                ],
            ),
            Map(
                [DateTime("2020-11-13T11:00"),
                 DateTime("2020-11-13T12:00")],
                [
                    TimeSeriesVariableResolution(
                        ["2020-11-13T11:00", "2020-11-13T12:00"], [-5.5, -6.6],
                        False, False),
                    TimeSeriesVariableResolution(
                        ["2020-11-13T12:00", "2020-11-13T13:00"], [-7.7, -8.8],
                        False, False),
                ],
            ),
        ],
    )
    data = {
        ('1', 'int_col', 'base_alternative'):
        '-3',
        ('2', 'int_col', 'base_alternative'):
        '-1',
        ('3', 'int_col', 'base_alternative'):
        '2',
        ('1', 'float_col', 'base_alternative'):
        '1.1',
        ('2', 'float_col', 'base_alternative'):
        '1.2',
        ('3', 'float_col', 'base_alternative'):
        '1.3',
        (
            '1',
            'time_series_col',
            'base_alternative',
        ):
        '{"type": "time_series", "data": {"2019-07-10T13:00": 2.3, "2019-07-10T13:20": 5.0}}',
        (
            '2',
            'time_series_col',
            'base_alternative',
        ):
        '{"type": "time_series", "index": {"start": "2019-07-10T13:00", "resolution": "20 minutes"}, "data": [3.3, 4.0]}',
        (
            '3',
            'time_series_col',
            'base_alternative',
        ):
        '{"type": "time_series", "data": {"2019-07-10T13:00": 4.3, "2019-07-10T13:20": 3.0}}',
        ("1", "map_col", "base_alternative"):
        to_database(simple_map),
        ("2", "map_col", "base_alternative"):
        to_database(nested_map),
        ("3", "map_col", "base_alternative"):
        to_database(nested_map_with_time_series),
    }
    data = {
        tuple((db, k) for k in key) + (db, ): (db, value)
        for key, value in data.items()
    }
    spine_db_editor.load_parameter_value_data = lambda: data
    spine_db_editor.pivot_table_model = model = ParameterValuePivotTableModel(
        spine_db_editor)
    with patch.object(
            SpineDBEditor, "current_object_class_ids",
            new_callable=PropertyMock) as mock_current_object_class_ids:
        mock_current_object_class_ids.return_value = {"object": {db: 1}}
        model.call_reset_model(pivot=(['object'], ['parameter', 'alternative'],
                                      ['database'], (db, )))
    model.start_fetching()
    spine_db_editor.pivot_table_model = model
    spine_db_editor.pivot_table_proxy.setSourceModel(model)
    return spine_db_editor.pivot_table_proxy