From fa4dfa0d87c1b63a54351f4c436ea7636cbd9fd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A5kon=20V=2E=20Treider?= Date: Fri, 5 Sep 2025 15:48:56 +0200 Subject: [PATCH 1/3] add setting to pyproject to make ruff fix docstrings --- pyproject.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index cf614b4a82..53451baf30 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,6 +31,11 @@ external = ["DOC"] # let scripts use print statements "scripts/*" = ["T201"] +[tool.ruff.format] +# format code examples in docstrings to avoid users scrolling horizontally +docstring-code-format = true +docstring-code-line-length = 85 + [tool.poetry.dependencies] python = "^3.10" From 9c2e39deccb500c5ad3e502a577b271f9b1da6e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A5kon=20V=2E=20Treider?= Date: Fri, 20 Mar 2026 09:33:13 +0100 Subject: [PATCH 2/3] auto-format docstring with ruff --- cognite/client/_api/agents/agents.py | 51 ++-- cognite/client/_api/ai/tools/documents.py | 4 +- cognite/client/_api/annotations.py | 4 +- cognite/client/_api/assets.py | 65 +++-- .../client/_api/data_modeling/containers.py | 84 +++--- .../client/_api/data_modeling/data_models.py | 17 +- cognite/client/_api/data_modeling/graphql.py | 2 +- .../client/_api/data_modeling/instances.py | 262 +++++++++++------- .../_api/data_modeling/space_statistics.py | 4 +- cognite/client/_api/data_modeling/spaces.py | 16 +- cognite/client/_api/data_modeling/views.py | 26 +- cognite/client/_api/data_sets.py | 10 +- cognite/client/_api/datapoints.py | 197 ++++++++----- .../client/_api/datapoints_subscriptions.py | 27 +- cognite/client/_api/diagrams.py | 17 +- cognite/client/_api/document_preview.py | 4 +- cognite/client/_api/documents.py | 30 +- cognite/client/_api/entity_matching.py | 26 +- cognite/client/_api/events.py | 42 ++- .../_api/extractionpipelines/__init__.py | 6 +- .../_api/extractionpipelines/configs.py | 4 +- .../client/_api/extractionpipelines/runs.py | 11 +- cognite/client/_api/files.py | 42 ++- cognite/client/_api/functions/__init__.py | 8 +- cognite/client/_api/functions/schedules.py | 8 +- cognite/client/_api/geospatial.py | 241 +++++++++------- .../_api/hosted_extractors/destinations.py | 21 +- cognite/client/_api/hosted_extractors/jobs.py | 14 +- .../client/_api/hosted_extractors/mappings.py | 17 +- .../client/_api/hosted_extractors/sources.py | 16 +- cognite/client/_api/iam/__init__.py | 28 +- cognite/client/_api/iam/groups.py | 13 +- cognite/client/_api/labels.py | 9 +- .../client/_api/postgres_gateway/tables.py | 15 +- cognite/client/_api/postgres_gateway/users.py | 20 +- cognite/client/_api/raw/databases.py | 2 +- cognite/client/_api/raw/rows.py | 15 +- cognite/client/_api/raw/tables.py | 2 +- cognite/client/_api/relationships.py | 20 +- cognite/client/_api/sequence_data.py | 39 ++- cognite/client/_api/sequences.py | 94 +++++-- .../client/_api/simulators/integrations.py | 2 +- cognite/client/_api/simulators/models.py | 25 +- .../_api/simulators/models_revisions.py | 14 +- .../_api/simulators/routine_revisions.py | 6 +- cognite/client/_api/simulators/routines.py | 16 +- cognite/client/_api/simulators/runs.py | 3 +- cognite/client/_api/synthetic_time_series.py | 10 +- cognite/client/_api/three_d/asset_mapping.py | 11 +- cognite/client/_api/three_d/models.py | 16 +- cognite/client/_api/three_d/revisions.py | 22 +- cognite/client/_api/time_series.py | 74 +++-- .../client/_api/transformations/__init__.py | 31 ++- .../_api/transformations/notifications.py | 2 +- .../client/_api/transformations/schedules.py | 6 +- cognite/client/_api/units.py | 8 +- cognite/client/_api/vision.py | 4 +- cognite/client/_api/workflows/executions.py | 11 +- cognite/client/_api/workflows/tasks.py | 8 +- cognite/client/_api/workflows/triggers.py | 28 +- cognite/client/_api/workflows/versions.py | 28 +- cognite/client/_sync_api/agents/agents.py | 51 ++-- .../client/_sync_api/ai/tools/documents.py | 4 +- cognite/client/_sync_api/annotations.py | 4 +- cognite/client/_sync_api/assets.py | 65 +++-- .../_sync_api/data_modeling/containers.py | 84 +++--- .../_sync_api/data_modeling/data_models.py | 17 +- .../client/_sync_api/data_modeling/graphql.py | 2 +- .../_sync_api/data_modeling/instances.py | 262 +++++++++++------- .../data_modeling/space_statistics.py | 4 +- .../client/_sync_api/data_modeling/spaces.py | 16 +- .../client/_sync_api/data_modeling/views.py | 26 +- cognite/client/_sync_api/data_sets.py | 10 +- cognite/client/_sync_api/datapoints.py | 197 ++++++++----- .../_sync_api/datapoints_subscriptions.py | 27 +- cognite/client/_sync_api/diagrams.py | 17 +- cognite/client/_sync_api/document_preview.py | 4 +- cognite/client/_sync_api/documents.py | 30 +- cognite/client/_sync_api/entity_matching.py | 26 +- cognite/client/_sync_api/events.py | 42 ++- .../_sync_api/extractionpipelines/__init__.py | 6 +- .../_sync_api/extractionpipelines/configs.py | 4 +- .../_sync_api/extractionpipelines/runs.py | 11 +- cognite/client/_sync_api/files.py | 42 ++- .../client/_sync_api/functions/__init__.py | 8 +- .../client/_sync_api/functions/schedules.py | 8 +- cognite/client/_sync_api/geospatial.py | 241 +++++++++------- .../hosted_extractors/destinations.py | 21 +- .../_sync_api/hosted_extractors/jobs.py | 14 +- .../_sync_api/hosted_extractors/mappings.py | 17 +- .../_sync_api/hosted_extractors/sources.py | 16 +- cognite/client/_sync_api/iam/__init__.py | 28 +- cognite/client/_sync_api/iam/groups.py | 13 +- cognite/client/_sync_api/labels.py | 9 +- .../_sync_api/postgres_gateway/tables.py | 15 +- .../_sync_api/postgres_gateway/users.py | 20 +- cognite/client/_sync_api/raw/databases.py | 2 +- cognite/client/_sync_api/raw/rows.py | 15 +- cognite/client/_sync_api/raw/tables.py | 2 +- cognite/client/_sync_api/relationships.py | 20 +- cognite/client/_sync_api/sequence_data.py | 39 ++- cognite/client/_sync_api/sequences.py | 94 +++++-- .../_sync_api/simulators/integrations.py | 2 +- cognite/client/_sync_api/simulators/models.py | 25 +- .../_sync_api/simulators/models_revisions.py | 14 +- .../_sync_api/simulators/routine_revisions.py | 6 +- .../client/_sync_api/simulators/routines.py | 16 +- cognite/client/_sync_api/simulators/runs.py | 3 +- .../client/_sync_api/synthetic_time_series.py | 10 +- .../client/_sync_api/three_d/asset_mapping.py | 11 +- cognite/client/_sync_api/three_d/models.py | 16 +- cognite/client/_sync_api/three_d/revisions.py | 22 +- cognite/client/_sync_api/time_series.py | 74 +++-- .../_sync_api/transformations/__init__.py | 31 ++- .../transformations/notifications.py | 2 +- .../_sync_api/transformations/schedules.py | 6 +- cognite/client/_sync_api/units.py | 8 +- cognite/client/_sync_api/vision.py | 4 +- .../client/_sync_api/workflows/executions.py | 11 +- cognite/client/_sync_api/workflows/tasks.py | 8 +- .../client/_sync_api/workflows/triggers.py | 28 +- .../client/_sync_api/workflows/versions.py | 28 +- cognite/client/credentials.py | 4 +- .../client/data_classes/contextualization.py | 7 +- cognite/client/data_classes/filters.py | 28 +- cognite/client/data_classes/geospatial.py | 13 +- .../data_classes/transformations/jobs.py | 14 +- cognite/client/data_classes/workflows.py | 4 +- cognite/client/testing.py | 4 +- cognite/client/utils/_time.py | 4 +- 130 files changed, 2422 insertions(+), 1372 deletions(-) diff --git a/cognite/client/_api/agents/agents.py b/cognite/client/_api/agents/agents.py index 0a277bfbb7..9064672eef 100644 --- a/cognite/client/_api/agents/agents.py +++ b/cognite/client/_api/agents/agents.py @@ -54,10 +54,9 @@ async def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | A ... AgentUpsert, ... QueryKnowledgeGraphAgentToolUpsert, ... QueryKnowledgeGraphAgentToolConfiguration, - ... DataModelInfo + ... DataModelInfo, ... ) >>> client = CogniteClient() - ... >>> find_assets_tool = QueryKnowledgeGraphAgentToolUpsert( ... name="find assets", ... description="Use this tool to find assets", @@ -70,13 +69,13 @@ async def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | A ... view_external_ids=["CogniteAsset"], ... ) ... ] - ... ) + ... ), ... ) >>> agent = AgentUpsert( ... external_id="my_agent", ... name="My Agent", ... labels=["published"], - ... tools=[find_assets_tool] + ... tools=[find_assets_tool], ... ) >>> client.agents.upsert(agents=[agent]) @@ -89,9 +88,8 @@ async def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | A ... DataModelInfo, ... SummarizeDocumentAgentToolUpsert, ... AskDocumentAgentToolUpsert, - ... QueryTimeSeriesDatapointsAgentToolUpsert + ... QueryTimeSeriesDatapointsAgentToolUpsert, ... ) - ... >>> find_assets_tool = QueryKnowledgeGraphAgentToolUpsert( ... name="find assets", ... description="Use this tool to query the knowledge graph for assets", @@ -104,7 +102,7 @@ async def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | A ... view_external_ids=["CogniteAsset"], ... ) ... ] - ... ) + ... ), ... ) >>> find_files_tool = QueryKnowledgeGraphAgentToolUpsert( ... name="find files", @@ -118,7 +116,7 @@ async def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | A ... view_external_ids=["CogniteFile"], ... ) ... ] - ... ) + ... ), ... ) >>> find_time_series_tool = QueryKnowledgeGraphAgentToolUpsert( ... name="find time series", @@ -132,19 +130,19 @@ async def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | A ... view_external_ids=["CogniteTimeSeries"], ... ) ... ] - ... ) + ... ), ... ) >>> summarize_tool = SummarizeDocumentAgentToolUpsert( ... name="summarize document", - ... description="Use this tool to get a summary of a document" + ... description="Use this tool to get a summary of a document", ... ) >>> ask_doc_tool = AskDocumentAgentToolUpsert( ... name="ask document", - ... description="Use this tool to ask questions about specific documents" + ... description="Use this tool to ask questions about specific documents", ... ) >>> ts_tool = QueryTimeSeriesDatapointsAgentToolUpsert( ... name="query time series", - ... description="Use this tool to query time series data points" + ... description="Use this tool to query time series data points", ... ) >>> agent = AgentUpsert( ... external_id="my_agent", @@ -152,7 +150,14 @@ async def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | A ... description="An agent with many tools", ... instructions="You are a helpful assistant that can query knowledge graphs, summarize documents, answer questions about documents, and query time series data points.", ... labels=["published"], - ... tools=[find_assets_tool, find_files_tool, find_time_series_tool, summarize_tool, ask_doc_tool, ts_tool] + ... tools=[ + ... find_assets_tool, + ... find_files_tool, + ... find_time_series_tool, + ... summarize_tool, + ... ask_doc_tool, + ... ts_tool, + ... ], ... ) >>> client.agents.upsert(agents=[agent]) @@ -281,8 +286,7 @@ async def chat( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> response = client.agents.chat( - ... agent_external_id="my_agent", - ... messages=Message("What can you help me with?") + ... agent_external_id="my_agent", messages=Message("What can you help me with?") ... ) >>> print(response.text) @@ -291,7 +295,7 @@ async def chat( >>> follow_up = client.agents.chat( ... agent_external_id="my_agent", ... messages=Message("Tell me more about that"), - ... cursor=response.cursor + ... cursor=response.cursor, ... ) Send multiple messages at once: @@ -300,8 +304,8 @@ async def chat( ... agent_external_id="my_agent", ... messages=[ ... Message("Help me find the 1st stage compressor."), - ... Message("Once you have found it, find related time series.") - ... ] + ... Message("Once you have found it, find related time series."), + ... ], ... ) Chat with client-side actions: @@ -316,13 +320,13 @@ async def chat( ... "a": {"type": "number", "description": "First number"}, ... "b": {"type": "number", "description": "Second number"}, ... }, - ... "required": ["a", "b"] - ... } + ... "required": ["a", "b"], + ... }, ... ) >>> response = client.agents.chat( ... agent_external_id="my_agent", ... messages=Message("What is 42 plus 58?"), - ... actions=[add_numbers_action] + ... actions=[add_numbers_action], ... ) >>> if response.action_calls: ... for call in response.action_calls: @@ -332,11 +336,10 @@ async def chat( ... response = client.agents.chat( ... agent_external_id="my_agent", ... messages=ClientToolResult( - ... action_id=call.action_id, - ... content=f"The result is {result}" + ... action_id=call.action_id, content=f"The result is {result}" ... ), ... cursor=response.cursor, - ... actions=[add_numbers_action] + ... actions=[add_numbers_action], ... ) """ self._warnings.warn() diff --git a/cognite/client/_api/ai/tools/documents.py b/cognite/client/_api/ai/tools/documents.py index 42ea16dce2..825d22fc02 100644 --- a/cognite/client/_api/ai/tools/documents.py +++ b/cognite/client/_api/ai/tools/documents.py @@ -44,9 +44,7 @@ async def summarize( You can also use external ID or instance ID: >>> from cognite.client.data_classes.data_modeling import NodeId - >>> client.ai.tools.documents.summarize( - ... instance_id=NodeId("my-space", "my-xid") - ... ) + >>> client.ai.tools.documents.summarize(instance_id=NodeId("my-space", "my-xid")) """ ident = IdentifierSequenceWithInstanceId.load(id, external_id, instance_id).as_singleton() res = await self._post( diff --git a/cognite/client/_api/annotations.py b/cognite/client/_api/annotations.py index 960ea62997..3584b4befc 100644 --- a/cognite/client/_api/annotations.py +++ b/cognite/client/_api/annotations.py @@ -239,7 +239,9 @@ async def list(self, filter: AnnotationFilter | dict, limit: int | None = DEFAUL >>> from cognite.client.data_classes import AnnotationFilter >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> flt = AnnotationFilter(annotated_resource_type="file", annotated_resource_ids=[{"id": 123}]) + >>> flt = AnnotationFilter( + ... annotated_resource_type="file", annotated_resource_ids=[{"id": 123}] + ... ) >>> res = client.annotations.list(flt, limit=None) """ assert_type(filter, "filter", [AnnotationFilter, dict], allow_none=False) diff --git a/cognite/client/_api/assets.py b/cognite/client/_api/assets.py index f3bb7ec5e2..afd9c7828f 100644 --- a/cognite/client/_api/assets.py +++ b/cognite/client/_api/assets.py @@ -262,7 +262,9 @@ async def retrieve_multiple( Get assets by external id: - >>> res = client.assets.retrieve_multiple(external_ids=["abc", "def"], ignore_unknown_ids=True) + >>> res = client.assets.retrieve_multiple( + ... external_ids=["abc", "def"], ignore_unknown_ids=True + ... ) """ identifiers = IdentifierSequence.load(ids=ids, external_ids=external_ids) return await self._retrieve_multiple( @@ -343,8 +345,8 @@ async def aggregate_cardinality_values( >>> from cognite.client.data_classes.assets import AssetProperty >>> is_critical = Search(AssetProperty.description, "critical") >>> critical_assets = client.assets.aggregate_cardinality_values( - ... AssetProperty.metadata_key("timezone"), - ... advanced_filter=is_critical) + ... AssetProperty.metadata_key("timezone"), advanced_filter=is_critical + ... ) """ self._validate_filter(advanced_filter) return await self._advanced_aggregate( @@ -421,7 +423,9 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes.assets import AssetProperty >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> result = client.assets.aggregate_unique_values(AssetProperty.metadata_key("timezone")) + >>> result = client.assets.aggregate_unique_values( + ... AssetProperty.metadata_key("timezone") + ... ) >>> print(result.unique) Get the different labels with count used for assets created after 2020-01-01 in your CDF project: @@ -430,8 +434,12 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes.assets import AssetProperty >>> from cognite.client.utils import timestamp_to_ms >>> from datetime import datetime - >>> created_after_2020 = filters.Range(AssetProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.assets.aggregate_unique_values(AssetProperty.labels, advanced_filter=created_after_2020) + >>> created_after_2020 = filters.Range( + ... AssetProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.assets.aggregate_unique_values( + ... AssetProperty.labels, advanced_filter=created_after_2020 + ... ) >>> print(result.unique) Get the different labels with count for assets updated after 2020-01-01 in your CDF project, but exclude all labels that @@ -441,8 +449,14 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes import aggregations >>> from cognite.client.data_classes import filters >>> not_test = aggregations.Not(aggregations.Prefix("test")) - >>> created_after_2020 = filters.Range(AssetProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.assets.aggregate_unique_values(AssetProperty.labels, advanced_filter=created_after_2020, aggregate_filter=not_test) + >>> created_after_2020 = filters.Range( + ... AssetProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.assets.aggregate_unique_values( + ... AssetProperty.labels, + ... advanced_filter=created_after_2020, + ... aggregate_filter=not_test, + ... ) >>> print(result.unique) """ @@ -600,7 +614,8 @@ async def create_hierarchy( >>> assets = [ ... AssetWrite(external_id="root", name="root"), ... AssetWrite(external_id="child1", parent_external_id="root", name="child1"), - ... AssetWrite(external_id="child2", parent_external_id="root", name="child2")] + ... AssetWrite(external_id="child2", parent_external_id="root", name="child2"), + ... ] >>> res = client.assets.create_hierarchy(assets) Create an asset hierarchy, but run update for existing assets: @@ -692,7 +707,7 @@ async def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.assets.delete(id=[1,2,3], external_id="3") + >>> client.assets.delete(id=[1, 2, 3], external_id="3") """ await self._delete_multiple( identifiers=IdentifierSequence.load(ids=id, external_ids=external_id), @@ -735,7 +750,11 @@ async def update( >>> from cognite.client.data_classes import AssetUpdate >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> my_update = AssetUpdate(id=1).description.set("New description").metadata.add({"key": "value"}) + >>> my_update = ( + ... AssetUpdate(id=1) + ... .description.set("New description") + ... .metadata.add({"key": "value"}) + ... ) >>> res1 = client.assets.update(my_update) >>> # Remove an already set field like so >>> another_update = AssetUpdate(id=1).description.set(None) @@ -807,7 +826,9 @@ async def upsert( >>> # async_client = AsyncCogniteClient() # another option >>> existing_asset = client.assets.retrieve(id=1) >>> existing_asset.description = "New description" - >>> new_asset = AssetWrite(external_id="new_asset", name="my asset", description="New asset") + >>> new_asset = AssetWrite( + ... external_id="new_asset", name="my asset", description="New asset" + ... ) >>> res = client.assets.upsert([existing_asset, new_asset], mode="replace") """ return await self._upsert_multiple( @@ -862,12 +883,14 @@ async def search( Search for assets using multiple filters, finding all assets with name similar to `xyz` with parent asset `123` or `456` with source `some source`: - >>> res = client.assets.search(name="xyz",filter={"parent_ids": [123,456],"source": "some source"}) + >>> res = client.assets.search( + ... name="xyz", filter={"parent_ids": [123, 456], "source": "some source"} + ... ) Search for an asset with an attached label: >>> my_label_filter = LabelFilter(contains_all=["PUMP"]) - >>> res = client.assets.search(name="xyz",filter=AssetFilter(labels=my_label_filter)) + >>> res = client.assets.search(name="xyz", filter=AssetFilter(labels=my_label_filter)) """ return await self._search( list_cls=AssetList, @@ -988,7 +1011,7 @@ async def list( Iterate over chunks of assets to reduce memory load: >>> for asset_list in client.assets(chunk_size=2500): - ... asset_list # do something with the assets + ... asset_list # do something with the assets Filter assets based on labels: @@ -1013,17 +1036,19 @@ async def list( >>> from cognite.client.data_classes.assets import AssetProperty, SortableAssetProperty >>> in_timezone = filters.Prefix(AssetProperty.metadata_key("timezone"), "Europe") >>> res = client.assets.list( - ... advanced_filter=in_timezone, - ... sort=(SortableAssetProperty.external_id, "asc")) + ... advanced_filter=in_timezone, sort=(SortableAssetProperty.external_id, "asc") + ... ) Combine filter and advanced filter: >>> from cognite.client.data_classes import filters >>> not_instrument_lvl5 = filters.And( - ... filters.ContainsAny("labels", ["Level5"]), - ... filters.Not(filters.ContainsAny("labels", ["Instrument"])) + ... filters.ContainsAny("labels", ["Level5"]), + ... filters.Not(filters.ContainsAny("labels", ["Instrument"])), + ... ) + >>> res = client.assets.list( + ... asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5 ... ) - >>> res = client.assets.list(asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5) """ agg_props = self._process_aggregated_props(aggregated_properties) diff --git a/cognite/client/_api/data_modeling/containers.py b/cognite/client/_api/data_modeling/containers.py index cf74ebf750..ea94a49d4d 100644 --- a/cognite/client/_api/data_modeling/containers.py +++ b/cognite/client/_api/data_modeling/containers.py @@ -114,13 +114,14 @@ async def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.data_modeling.containers.retrieve(('mySpace', 'myContainer')) + >>> res = client.data_modeling.containers.retrieve(("mySpace", "myContainer")) Fetch using the ContainerId: >>> from cognite.client.data_classes.data_modeling import ContainerId >>> res = client.data_modeling.containers.retrieve( - ... ContainerId(space='mySpace', external_id='myContainer')) + ... ContainerId(space="mySpace", external_id="myContainer") + ... ) """ identifier = _load_identifier(ids, "container") return await self._retrieve_multiple( @@ -253,7 +254,7 @@ async def list( Iterate over chunks of containers to reduce memory load: >>> for container_list in client.data_modeling.containers(chunk_size=10): - ... container_list # do something with the containers + ... container_list # do something with the containers """ flt = _ContainerFilter(space, include_global) return await self._list( @@ -286,20 +287,26 @@ async def apply(self, container: ContainerApply | Sequence[ContainerApply]) -> C >>> from cognite.client import CogniteClient >>> from cognite.client.data_classes.data_modeling import ( - ... ContainerApply, ContainerPropertyApply, Text, Float64) + ... ContainerApply, + ... ContainerPropertyApply, + ... Text, + ... Float64, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> container = ContainerApply( - ... space="mySpace", - ... external_id="myContainer", - ... properties={ - ... "name": ContainerPropertyApply(type=Text, name="name"), - ... "numbers": ContainerPropertyApply( - ... type=Float64(is_list=True, max_list_size=200), - ... description="very important numbers", - ... ), - ... }, - ... ), + >>> container = ( + ... ContainerApply( + ... space="mySpace", + ... external_id="myContainer", + ... properties={ + ... "name": ContainerPropertyApply(type=Text, name="name"), + ... "numbers": ContainerPropertyApply( + ... type=Float64(is_list=True, max_list_size=200), + ... description="very important numbers", + ... ), + ... }, + ... ), + ... ) >>> res = client.data_modeling.containers.apply(container) Create new container with unit-aware properties: @@ -315,11 +322,8 @@ async def apply(self, container: ContainerApply | Sequence[ContainerApply]) -> C ... description="Maximum Pump Pressure", ... name="maxPressure", ... type=Float64( - ... unit=UnitReference( - ... external_id="pressure:bar", - ... source_unit="BAR" - ... ) - ... ) + ... unit=UnitReference(external_id="pressure:bar", source_unit="BAR") + ... ), ... ), ... "rotationConfigurations": ContainerPropertyApply( ... nullable=True, @@ -327,12 +331,10 @@ async def apply(self, container: ContainerApply | Sequence[ContainerApply]) -> C ... name="rotationConfigurations", ... type=Float64( ... is_list=True, - ... unit=UnitReference( - ... external_id="angular_velocity:rev-per-min" - ... ) - ... ) - ... ) - ... } + ... unit=UnitReference(external_id="angular_velocity:rev-per-min"), + ... ), + ... ), + ... }, ... ) >>> res = client.data_modeling.containers.apply(container) @@ -341,10 +343,25 @@ async def apply(self, container: ContainerApply | Sequence[ContainerApply]) -> C ``nullable``, ``auto_increment``, ``default_value`` and ``immutable`` that may be specified, depending on the choice of property type (e.g. ``auto_increment`` only works with integer types). - >>> from cognite.client.data_classes.data_modeling.data_types import UnitReference, EnumValue >>> from cognite.client.data_classes.data_modeling.data_types import ( - ... Boolean, Date, DirectRelation, Enum, FileReference, Float32, Float64, - ... Int32, Int64, Json, SequenceReference, Text, TimeSeriesReference, Timestamp + ... UnitReference, + ... EnumValue, + ... ) + >>> from cognite.client.data_classes.data_modeling.data_types import ( + ... Boolean, + ... Date, + ... DirectRelation, + ... Enum, + ... FileReference, + ... Float32, + ... Float64, + ... Int32, + ... Int64, + ... Json, + ... SequenceReference, + ... Text, + ... TimeSeriesReference, + ... Timestamp, ... ) >>> container_properties = { ... "prop01": ContainerPropertyApply(Boolean), @@ -361,8 +378,13 @@ async def apply(self, container: ContainerApply | Sequence[ContainerApply]) -> C ... "prop10": ContainerPropertyApply(DirectRelation(is_list=True)), ... # Note: Enum also support `unknown_value`: The value to use when the enum value is unknown. ... "prop11": ContainerPropertyApply( - ... Enum({"Closed": EnumValue("Valve is closed"), - ... "Opened": EnumValue("Valve is opened")})), + ... Enum( + ... { + ... "Closed": EnumValue("Valve is closed"), + ... "Opened": EnumValue("Valve is opened"), + ... } + ... ) + ... ), ... # Note: Floats support unit references, e.g. `unit=UnitReference("pressure:bar")`: ... "prop12": ContainerPropertyApply(Float32), ... "prop13": ContainerPropertyApply(Float32(is_list=True)), diff --git a/cognite/client/_api/data_modeling/data_models.py b/cognite/client/_api/data_modeling/data_models.py index aa85334815..3b464999d0 100644 --- a/cognite/client/_api/data_modeling/data_models.py +++ b/cognite/client/_api/data_modeling/data_models.py @@ -218,7 +218,7 @@ async def list( Iterate over chunks of data model to reduce memory load: >>> for data_model_list in client.data_modeling.data_models(chunk_size=10): - ... data_model_list # do something with the data model + ... data_model_list # do something with the data model """ filter = DataModelFilter(space, inline_views, all_versions, include_global) @@ -255,8 +255,19 @@ async def apply(self, data_model: DataModelApply | Sequence[DataModelApply]) -> >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> data_models = [ - ... DataModelApply(space="mySpace",external_id="myDataModel",version="v1",views=[ViewId("mySpace","myView","v1")]), - ... DataModelApply(space="mySpace",external_id="myOtherDataModel",version="v1",views=[ViewId("mySpace","myView","v1")])] + ... DataModelApply( + ... space="mySpace", + ... external_id="myDataModel", + ... version="v1", + ... views=[ViewId("mySpace", "myView", "v1")], + ... ), + ... DataModelApply( + ... space="mySpace", + ... external_id="myOtherDataModel", + ... version="v1", + ... views=[ViewId("mySpace", "myView", "v1")], + ... ), + ... ] >>> res = client.data_modeling.data_models.apply(data_models) """ return await self._create_multiple( diff --git a/cognite/client/_api/data_modeling/graphql.py b/cognite/client/_api/data_modeling/graphql.py index 58d0943c36..7f6bd3a6da 100644 --- a/cognite/client/_api/data_modeling/graphql.py +++ b/cognite/client/_api/data_modeling/graphql.py @@ -102,7 +102,7 @@ async def apply_dml( ... id=("mySpaceExternalId", "myModelExternalId", "1"), ... dml="type MyType { id: String! }", ... name="My model name", - ... description="My model description" + ... description="My model description", ... ) """ graphql_body = """ diff --git a/cognite/client/_api/data_modeling/instances.py b/cognite/client/_api/data_modeling/instances.py index f59fc4abb7..de91cc1497 100644 --- a/cognite/client/_api/data_modeling/instances.py +++ b/cognite/client/_api/data_modeling/instances.py @@ -384,32 +384,45 @@ async def retrieve_edges( We strongly suggest you use snake_cased attribute names, as is done here: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.data_modeling import EdgeId, TypedEdge, PropertyOptions, DirectRelationReference, ViewId + >>> from cognite.client.data_classes.data_modeling import ( + ... EdgeId, + ... TypedEdge, + ... PropertyOptions, + ... DirectRelationReference, + ... ViewId, + ... ) >>> class Flow(TypedEdge): - ... flow_rate = PropertyOptions(identifier="flowRate") - ... - ... def __init__( - ... self, - ... space: str, - ... external_id: str, - ... version: int, - ... type: DirectRelationReference, - ... last_updated_time: int, - ... created_time: int, - ... flow_rate: float, - ... start_node: DirectRelationReference, - ... end_node: DirectRelationReference, - ... deleted_time: int | None = None, - ... ) -> None: - ... super().__init__( - ... space, external_id, version, type, last_updated_time, created_time, start_node, end_node, deleted_time - ... ) - ... self.flow_rate = flow_rate + ... flow_rate = PropertyOptions(identifier="flowRate") ... - ... @classmethod - ... def get_source(cls) -> ViewId: - ... return ViewId("sp_model_space", "flow", "1") + ... def __init__( + ... self, + ... space: str, + ... external_id: str, + ... version: int, + ... type: DirectRelationReference, + ... last_updated_time: int, + ... created_time: int, + ... flow_rate: float, + ... start_node: DirectRelationReference, + ... end_node: DirectRelationReference, + ... deleted_time: int | None = None, + ... ) -> None: + ... super().__init__( + ... space, + ... external_id, + ... version, + ... type, + ... last_updated_time, + ... created_time, + ... start_node, + ... end_node, + ... deleted_time, + ... ) + ... self.flow_rate = flow_rate ... + ... @classmethod + ... def get_source(cls) -> ViewId: + ... return ViewId("sp_model_space", "flow", "1") >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> res = client.data_modeling.instances.retrieve_edges( @@ -488,38 +501,43 @@ async def retrieve_nodes( We strongly suggest you use snake_cased attribute names, as is done here: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.data_modeling import NodeId, TypedNode, PropertyOptions, DirectRelationReference, ViewId + >>> from cognite.client.data_classes.data_modeling import ( + ... NodeId, + ... TypedNode, + ... PropertyOptions, + ... DirectRelationReference, + ... ViewId, + ... ) >>> class Person(TypedNode): - ... birth_year = PropertyOptions(identifier="birthYear") - ... - ... def __init__( - ... self, - ... space: str, - ... external_id: str, - ... version: int, - ... last_updated_time: int, - ... created_time: int, - ... name: str, - ... birth_year: int | None = None, - ... type: DirectRelationReference | None = None, - ... deleted_time: int | None = None, - ... ): - ... super().__init__( - ... space=space, - ... external_id=external_id, - ... version=version, - ... last_updated_time=last_updated_time, - ... created_time=created_time, - ... type=type, - ... deleted_time=deleted_time - ... ) - ... self.name = name - ... self.birth_year = birth_year + ... birth_year = PropertyOptions(identifier="birthYear") ... - ... @classmethod - ... def get_source(cls) -> ViewId: - ... return ViewId("myModelSpace", "Person", "1") + ... def __init__( + ... self, + ... space: str, + ... external_id: str, + ... version: int, + ... last_updated_time: int, + ... created_time: int, + ... name: str, + ... birth_year: int | None = None, + ... type: DirectRelationReference | None = None, + ... deleted_time: int | None = None, + ... ): + ... super().__init__( + ... space=space, + ... external_id=external_id, + ... version=version, + ... last_updated_time=last_updated_time, + ... created_time=created_time, + ... type=type, + ... deleted_time=deleted_time, + ... ) + ... self.name = name + ... self.birth_year = birth_year ... + ... @classmethod + ... def get_source(cls) -> ViewId: + ... return ViewId("myModelSpace", "Person", "1") >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> res = client.data_modeling.instances.retrieve_nodes( @@ -562,7 +580,8 @@ async def retrieve( >>> res = client.data_modeling.instances.retrieve( ... nodes=("mySpace", "myNodeExternalId"), ... edges=("mySpace", "myEdgeExternalId"), - ... sources=("mySpace", "myViewExternalId", "myViewVersion")) + ... sources=("mySpace", "myViewExternalId", "myViewVersion"), + ... ) Retrieve nodes an edges using the built in data class @@ -570,7 +589,8 @@ async def retrieve( >>> res = client.data_modeling.instances.retrieve( ... NodeId("mySpace", "myNode"), ... EdgeId("mySpace", "myEdge"), - ... ViewId("mySpace", "myViewExternalId", "myViewVersion")) + ... ViewId("mySpace", "myViewExternalId", "myViewVersion"), + ... ) Retrieve nodes an edges using the the view object as source @@ -578,7 +598,8 @@ async def retrieve( >>> res = client.data_modeling.instances.retrieve( ... NodeId("mySpace", "myNode"), ... EdgeId("mySpace", "myEdge"), - ... sources=("myspace", "myView")) + ... sources=("myspace", "myView"), + ... ) """ return await self._retrieve_typed( nodes=nodes, edges=edges, sources=sources, include_typing=include_typing, node_cls=Node, edge_cls=Edge @@ -710,13 +731,17 @@ async def delete( Delete nodes and edges using the built in data class >>> from cognite.client.data_classes.data_modeling import NodeId, EdgeId - >>> client.data_modeling.instances.delete(NodeId('mySpace', 'myNode'), EdgeId('mySpace', 'myEdge')) + >>> client.data_modeling.instances.delete( + ... NodeId("mySpace", "myNode"), EdgeId("mySpace", "myEdge") + ... ) Delete all nodes from a NodeList >>> from cognite.client.data_classes.data_modeling import NodeId, EdgeId - >>> my_view = client.data_modeling.views.retrieve(('mySpace', 'myView')) - >>> my_nodes = client.data_modeling.instances.list(instance_type='node', sources=my_view, limit=None) + >>> my_view = client.data_modeling.views.retrieve(("mySpace", "myView")) + >>> my_nodes = client.data_modeling.instances.list( + ... instance_type="node", sources=my_view, limit=None + ... ) >>> client.data_modeling.instances.delete(nodes=my_nodes.as_ids()) """ identifiers = self._load_node_and_edge_ids(nodes, edges) @@ -832,7 +857,11 @@ async def subscribe( >>> from cognite.client import CogniteClient >>> from cognite.client.data_classes.data_modeling.query import ( - ... QuerySync, QueryResult, NodeResultSetExpressionSync, SelectSync, SourceSelector + ... QuerySync, + ... QueryResult, + ... NodeResultSetExpressionSync, + ... SelectSync, + ... SourceSelector, ... ) >>> from cognite.client.data_classes.data_modeling import ViewId >>> from cognite.client.data_classes.filters import Equals @@ -845,7 +874,7 @@ async def subscribe( >>> filter = Equals(view_id.as_property_ref("myAsset"), "Il-Tempo-Gigante") >>> query = QuerySync( ... with_={"work_orders": NodeResultSetExpressionSync(filter=filter)}, - ... select={"work_orders": SelectSync([SourceSelector(view_id, ["*"])])} + ... select={"work_orders": SelectSync([SourceSelector(view_id, ["*"])])}, ... ) >>> subscription_context = client.data_modeling.instances.subscribe( ... query, callback=just_print_the_result @@ -971,7 +1000,11 @@ async def apply( Create new node without data: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.data_modeling import EdgeApply, NodeOrEdgeData, NodeApply + >>> from cognite.client.data_classes.data_modeling import ( + ... EdgeApply, + ... NodeOrEdgeData, + ... NodeApply, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> node = NodeApply("mySpace", "myNodeId") @@ -979,7 +1012,13 @@ async def apply( Create two nodes with data with a one-to-many edge - >>> from cognite.client.data_classes.data_modeling import ContainerId, EdgeApply, NodeOrEdgeData, NodeApply, ViewId + >>> from cognite.client.data_classes.data_modeling import ( + ... ContainerId, + ... EdgeApply, + ... NodeOrEdgeData, + ... NodeApply, + ... ViewId, + ... ) >>> work_order = NodeApply( ... space="industrial", ... external_id="work_order:123", @@ -987,9 +1026,9 @@ async def apply( ... # Insert data through a view ... NodeOrEdgeData( ... ViewId("mySpace", "WorkOrderView", "v1"), - ... {"title": "Repair pump", "createdYear": 2023} + ... {"title": "Repair pump", "createdYear": 2023}, ... ) - ... ] + ... ], ... ) >>> pump = NodeApply( ... space="industrial", @@ -998,9 +1037,9 @@ async def apply( ... # Insert data directly to the container ... NodeOrEdgeData( ... ContainerId("mySpace", "PumpContainer"), - ... {"name": "Pump 456", "location": "Subsea"} + ... {"name": "Pump 456", "location": "Subsea"}, ... ) - ... ] + ... ], ... ) ... # This is one-to-many edge, in this case from a work order to a pump >>> work_order_to_pump = EdgeApply( @@ -1025,7 +1064,7 @@ async def apply( >>> res = client.data_modeling.instances.apply( ... edges=work_order_to_pump, ... auto_create_start_nodes=True, - ... auto_create_end_nodes=True + ... auto_create_end_nodes=True, ... ) Using helper function to create valid graphql timestamp for a datetime object: @@ -1033,7 +1072,9 @@ async def apply( >>> from cognite.client.utils import datetime_to_ms_iso_timestamp >>> from datetime import datetime, timezone >>> my_date = datetime(2020, 3, 14, 15, 9, 26, 535000, tzinfo=timezone.utc) - >>> data_model_timestamp = datetime_to_ms_iso_timestamp(my_date) # "2020-03-14T15:09:26.535+00:00" + >>> data_model_timestamp = datetime_to_ms_iso_timestamp( + ... my_date + ... ) # "2020-03-14T15:09:26.535+00:00" Create a typed node apply. Any property that you want to look up by a different attribute name, e.g. you want `my_node.birth_year` to return the data for property `birthYear`, must use the PropertyOptions as shown below. @@ -1047,9 +1088,9 @@ async def apply( ... super().__init__(space, external_id, type=("sp_model_space", "Person")) ... self.name = name ... self.birth_year = birth_year + ... ... def get_source(self): ... return ViewId("sp_model_space", "Person", "v1") - ... >>> person = PersonApply("sp_date_space", "my_person", "John Doe", 1980) >>> res = client.data_modeling.instances.apply(nodes=person) """ @@ -1193,10 +1234,7 @@ async def search( >>> # async_client = AsyncCogniteClient() # another option >>> view = ViewId("assetSpace", "EquipmentView", "v1") >>> res = client.data_modeling.instances.search( - ... view, - ... query="centrifugal pump", - ... properties=["description"], - ... operator="AND" + ... view, query="centrifugal pump", properties=["description"], operator="AND" ... ) Search for 'pump', 'valve' or 'compressor', but filter on those installed after 2015: @@ -1212,7 +1250,7 @@ async def search( ... query="pump valve compressor", ... properties=["name", "description"], ... filter=installed_after_2015, - ... operator="OR" + ... operator="OR", ... ) """ self._validate_filter(filter) @@ -1356,7 +1394,9 @@ async def aggregate( >>> # async_client = AsyncCogniteClient() # another option >>> avg_run_time = Average("runTimeMinutes") >>> view_id = ViewId("mySpace", "PumpView", "v1") - >>> res = client.data_modeling.instances.aggregate(view_id, avg_run_time, group_by="releaseYear") + >>> res = client.data_modeling.instances.aggregate( + ... view_id, avg_run_time, group_by="releaseYear" + ... ) """ if instance_type not in ("node", "edge"): @@ -1525,7 +1565,13 @@ async def query( Find work orders created before 2023 sorted by title: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.data_modeling.query import Query, Select, NodeResultSetExpression, EdgeResultSetExpression, SourceSelector + >>> from cognite.client.data_classes.data_modeling.query import ( + ... Query, + ... Select, + ... NodeResultSetExpression, + ... EdgeResultSetExpression, + ... SourceSelector, + ... ) >>> from cognite.client.data_classes.filters import Range, Equals >>> from cognite.client.data_classes.data_modeling.ids import ViewId >>> client = CogniteClient() @@ -1533,14 +1579,24 @@ async def query( >>> work_order_id = ViewId("mySpace", "WorkOrderView", "v1") >>> pump_id = ViewId("mySpace", "PumpView", "v1") >>> query = Query( - ... with_ = { - ... "work_orders": NodeResultSetExpression(filter=Range(work_order_id.as_property_ref("createdYear"), lt=2023)), - ... "work_orders_to_pumps": EdgeResultSetExpression(from_="work_orders", filter=Equals(["edge", "type"], {"space": work_order_id.space, "externalId": "WorkOrder.asset"})), + ... with_={ + ... "work_orders": NodeResultSetExpression( + ... filter=Range(work_order_id.as_property_ref("createdYear"), lt=2023) + ... ), + ... "work_orders_to_pumps": EdgeResultSetExpression( + ... from_="work_orders", + ... filter=Equals( + ... ["edge", "type"], + ... {"space": work_order_id.space, "externalId": "WorkOrder.asset"}, + ... ), + ... ), ... "pumps": NodeResultSetExpression(from_="work_orders_to_pumps"), ... }, - ... select = { + ... select={ ... "pumps": Select( - ... [SourceSelector(pump_id, ["name"])], sort=[InstanceSort(pump_id.as_property_ref("name"))]), + ... [SourceSelector(pump_id, ["name"])], + ... sort=[InstanceSort(pump_id.as_property_ref("name"))], + ... ), ... }, ... ) >>> res = client.data_modeling.instances.query(query) @@ -1549,7 +1605,10 @@ async def query( a UnitReference or a UnitSystemReference. Note that in order for a property to be converted, they need to have a unit defined in the underlying container. - >>> from cognite.client.data_classes.data_modeling.data_types import UnitReference, UnitSystemReference + >>> from cognite.client.data_classes.data_modeling.data_types import ( + ... UnitReference, + ... UnitSystemReference, + ... ) >>> selected_source = SourceSelector( ... source=ViewId("my-space", "my-xid", "v1"), ... properties=["f32_prop1", "f32_prop2", "f64_prop1", "f64_prop2"], @@ -1600,7 +1659,13 @@ async def sync( >>> from cognite.client import CogniteClient >>> from cognite.client.data_classes.data_modeling.instances import InstanceSort - >>> from cognite.client.data_classes.data_modeling.query import Query, Select, NodeResultSetExpression, EdgeResultSetExpression, SourceSelector + >>> from cognite.client.data_classes.data_modeling.query import ( + ... Query, + ... Select, + ... NodeResultSetExpression, + ... EdgeResultSetExpression, + ... SourceSelector, + ... ) >>> from cognite.client.data_classes.filters import Range, Equals >>> from cognite.client.data_classes.data_modeling.ids import ViewId >>> client = CogniteClient() @@ -1608,14 +1673,24 @@ async def sync( >>> work_order_id = ViewId("mySpace", "WorkOrderView", "v1") >>> pump_id = ViewId("mySpace", "PumpView", "v1") >>> query = Query( - ... with_ = { - ... "work_orders": NodeResultSetExpression(filter=Range(work_order_id.as_property_ref("createdYear"), lt=2023)), - ... "work_orders_to_pumps": EdgeResultSetExpression(from_="work_orders", filter=Equals(["edge", "type"], {"space": work_order_id.space, "externalId": "WorkOrder.asset"})), + ... with_={ + ... "work_orders": NodeResultSetExpression( + ... filter=Range(work_order_id.as_property_ref("createdYear"), lt=2023) + ... ), + ... "work_orders_to_pumps": EdgeResultSetExpression( + ... from_="work_orders", + ... filter=Equals( + ... ["edge", "type"], + ... {"space": work_order_id.space, "externalId": "WorkOrder.asset"}, + ... ), + ... ), ... "pumps": NodeResultSetExpression(from_="work_orders_to_pumps"), ... }, - ... select = { + ... select={ ... "pumps": Select( - ... [SourceSelector(pump_id, ["name"])], sort=[InstanceSort(pump_id.as_property_ref("name"))]), + ... [SourceSelector(pump_id, ["name"])], + ... sort=[InstanceSort(pump_id.as_property_ref("name"))], + ... ), ... }, ... ) >>> res = client.data_modeling.instances.sync(query) @@ -1763,9 +1838,10 @@ async def list( >>> from cognite.client.data_classes.data_modeling import InstanceSort >>> property_sort = InstanceSort( - ... property=('space', 'view_xid/view_version', 'some_property'), + ... property=("space", "view_xid/view_version", "some_property"), ... direction="descending", - ... nulls_first=True) + ... nulls_first=True, + ... ) >>> instance_list = client.data_modeling.instances.list(sort=property_sort) Iterate over instances (nodes by default), one-by-one: @@ -1778,7 +1854,7 @@ async def list( Iterate over chunks of instances to reduce memory load: >>> for instance_list in client.data_modeling.instances(chunk_size=100): - ... instance_list # do something with the instances + ... instance_list # do something with the instances List instances with a view as source: @@ -1804,9 +1880,7 @@ async def list( ... include_translated_query=True, # Include the internal representation of the query. ... profile=True, ... ) - >>> res = client.data_modeling.instances.list( - ... debug=debug_params, sources=my_view - ... ) + >>> res = client.data_modeling.instances.list(debug=debug_params, sources=my_view) >>> print(res.debug) """ self._validate_filter(filter) diff --git a/cognite/client/_api/data_modeling/space_statistics.py b/cognite/client/_api/data_modeling/space_statistics.py index dde3652fd7..26a7431a20 100644 --- a/cognite/client/_api/data_modeling/space_statistics.py +++ b/cognite/client/_api/data_modeling/space_statistics.py @@ -59,9 +59,7 @@ async def retrieve( >>> result = client.data_modeling.statistics.spaces.retrieve("my-space") Fetch statistics for multiple spaces: - >>> res = client.data_modeling.statistics.spaces.retrieve( - ... ["my-space1", "my-space2"] - ... ) + >>> res = client.data_modeling.statistics.spaces.retrieve(["my-space1", "my-space2"]) """ return await self._retrieve_multiple( diff --git a/cognite/client/_api/data_modeling/spaces.py b/cognite/client/_api/data_modeling/spaces.py index c0b801f232..3886d1f7f9 100644 --- a/cognite/client/_api/data_modeling/spaces.py +++ b/cognite/client/_api/data_modeling/spaces.py @@ -82,11 +82,13 @@ async def retrieve(self, spaces: str | SequenceNotStr[str]) -> Space | SpaceList >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.data_modeling.spaces.retrieve(spaces='mySpace') + >>> res = client.data_modeling.spaces.retrieve(spaces="mySpace") Get multiple spaces by id: - >>> res = client.data_modeling.spaces.retrieve(spaces=["MySpace", "MyAwesomeSpace", "MyOtherSpace"]) + >>> res = client.data_modeling.spaces.retrieve( + ... spaces=["MySpace", "MyAwesomeSpace", "MyOtherSpace"] + ... ) """ identifier = _load_space_identifier(spaces) @@ -155,7 +157,7 @@ async def list( Iterate over chunks of spaces to reduce memory load: >>> for space_list in client.data_modeling.spaces(chunk_size=2500): - ... space_list # do something with the spaces + ... space_list # do something with the spaces """ return await self._list( list_cls=SpaceList, @@ -189,8 +191,12 @@ async def apply(self, spaces: SpaceApply | Sequence[SpaceApply]) -> Space | Spac >>> from cognite.client.data_classes.data_modeling import SpaceApply >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> spaces = [SpaceApply(space="mySpace", description="My first space", name="My Space"), - ... SpaceApply(space="myOtherSpace", description="My second space", name="My Other Space")] + >>> spaces = [ + ... SpaceApply(space="mySpace", description="My first space", name="My Space"), + ... SpaceApply( + ... space="myOtherSpace", description="My second space", name="My Other Space" + ... ), + ... ] >>> res = client.data_modeling.spaces.apply(spaces) """ return await self._create_multiple( diff --git a/cognite/client/_api/data_modeling/views.py b/cognite/client/_api/data_modeling/views.py index b4c6c85107..f8ad74155b 100644 --- a/cognite/client/_api/data_modeling/views.py +++ b/cognite/client/_api/data_modeling/views.py @@ -124,7 +124,7 @@ async def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.data_modeling.views.retrieve(('mySpace', 'myView', 'v1')) + >>> res = client.data_modeling.views.retrieve(("mySpace", "myView", "v1")) """ identifier = _load_identifier(ids, "view") @@ -154,7 +154,7 @@ async def delete(self, ids: ViewIdentifier | Sequence[ViewIdentifier]) -> list[V >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.data_modeling.views.delete(('mySpace', 'myView', 'v1')) + >>> client.data_modeling.views.delete(("mySpace", "myView", "v1")) """ deleted_views = cast( list, @@ -204,7 +204,7 @@ async def list( Iterate over chunks of views to reduce memory load: >>> for view_list in client.data_modeling.views(chunk_size=10): - ... view_list # do something with the views + ... view_list # do something with the views """ filter_ = ViewFilter(space, include_inherited_properties, all_versions, include_global) @@ -237,7 +237,11 @@ async def apply(self, view: ViewApply | Sequence[ViewApply]) -> View | ViewList: Create new views: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.data_modeling import ViewApply, MappedPropertyApply, ContainerId + >>> from cognite.client.data_classes.data_modeling import ( + ... ViewApply, + ... MappedPropertyApply, + ... ContainerId, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> views = [ @@ -250,8 +254,8 @@ async def apply(self, view: ViewApply | Sequence[ViewApply]) -> View | ViewList: ... container=ContainerId("mySpace", "myContainer"), ... container_property_identifier="someProperty", ... ), - ... } - ... ) + ... }, + ... ) ... ] >>> res = client.data_modeling.views.apply(views) @@ -264,9 +268,11 @@ async def apply(self, view: ViewApply | Sequence[ViewApply]) -> View | ViewList: ... MappedPropertyApply, ... MultiEdgeConnectionApply, ... ViewApply, - ... ViewId + ... ViewId, + ... ) + >>> work_order_for_asset = DirectRelationReference( + ... space="mySpace", external_id="work_order_for_asset" ... ) - >>> work_order_for_asset = DirectRelationReference(space="mySpace", external_id="work_order_for_asset") >>> work_order_view = ViewApply( ... space="mySpace", ... external_id="WorkOrder", @@ -283,7 +289,7 @@ async def apply(self, view: ViewApply | Sequence[ViewApply]) -> View | ViewList: ... source=ViewId("mySpace", "Asset", "v1"), ... name="asset", ... ), - ... } + ... }, ... ) >>> asset_view = ViewApply( ... space="mySpace", @@ -302,7 +308,7 @@ async def apply(self, view: ViewApply | Sequence[ViewApply]) -> View | ViewList: ... source=ViewId("mySpace", "WorkOrder", "v1"), ... name="work_orders", ... ), - ... } + ... }, ... ) >>> res = client.data_modeling.views.apply([work_order_view, asset_view]) """ diff --git a/cognite/client/_api/data_sets.py b/cognite/client/_api/data_sets.py index c449b9dc85..acc84e003f 100644 --- a/cognite/client/_api/data_sets.py +++ b/cognite/client/_api/data_sets.py @@ -175,7 +175,9 @@ async def retrieve_multiple( Get data sets by external id: - >>> res = client.data_sets.retrieve_multiple(external_ids=["abc", "def"], ignore_unknown_ids=True) + >>> res = client.data_sets.retrieve_multiple( + ... external_ids=["abc", "def"], ignore_unknown_ids=True + ... ) """ identifiers = IdentifierSequence.load(ids=ids, external_ids=external_ids) return await self._retrieve_multiple( @@ -246,7 +248,9 @@ async def update( Perform a partial update on a data set, updating the description and removing a field from metadata: >>> from cognite.client.data_classes import DataSetUpdate - >>> my_update = DataSetUpdate(id=1).description.set("New description").metadata.remove(["key"]) + >>> my_update = ( + ... DataSetUpdate(id=1).description.set("New description").metadata.remove(["key"]) + ... ) >>> res = client.data_sets.update(my_update) """ return await self._update_multiple( @@ -292,7 +296,7 @@ async def list( Iterate over chunks of data sets to reduce memory load: >>> for data_set_list in client.data_sets(chunk_size=2500): - ... data_set_list # do something with the list + ... data_set_list # do something with the list """ filter = DataSetFilter( diff --git a/cognite/client/_api/datapoints.py b/cognite/client/_api/datapoints.py index 6e71af675c..004c4a402f 100644 --- a/cognite/client/_api/datapoints.py +++ b/cognite/client/_api/datapoints.py @@ -632,7 +632,7 @@ async def __call__( >>> queries = [ ... DatapointsQuery(id=123), ... DatapointsQuery(external_id="foo"), - ... DatapointsQuery(instance_id=NodeId("my-space", "my-ts-xid")) + ... DatapointsQuery(instance_id=NodeId("my-space", "my-ts-xid")), ... ] >>> for chunk_lst in client.time_series.data(query, return_arrays=False): ... if chunk_lst.get(id=123) is None: @@ -1046,11 +1046,12 @@ async def retrieve( (milliseconds after epoch). In the below example, we fetch them using their external ids: >>> dps_lst = client.time_series.data.retrieve( - ... external_id=["foo", "bar"], - ... start=1514764800000, - ... end=1546300800000, - ... aggregates=["max", "average"], - ... granularity="1d") + ... external_id=["foo", "bar"], + ... start=1514764800000, + ... end=1546300800000, + ... aggregates=["max", "average"], + ... granularity="1d", + ... ) In the two code examples above, we have a `dps` object (an instance of ``Datapoints``), and a `dps_lst` object (an instance of ``DatapointsList``). On `dps`, which in this case contains raw datapoints, you may access the underlying data directly by using the `.value` attribute. This works for @@ -1087,7 +1088,8 @@ async def retrieve( ... ], ... external_id=DatapointsQuery(external_id="foo", aggregates="max"), ... start="5d-ago", - ... granularity="1h") + ... granularity="1h", + ... ) Certain aggregates are very useful when they follow the calendar, for example electricity consumption per day, week, month or year. You may request such calendar-based aggregates in a specific timezone to make them even more useful: daylight savings (DST) @@ -1095,10 +1097,8 @@ async def retrieve( can be used independently. To get monthly local aggregates in Oslo, Norway you can do: >>> dps = client.time_series.data.retrieve( - ... id=123, - ... aggregates="sum", - ... granularity="1month", - ... timezone="Europe/Oslo") + ... id=123, aggregates="sum", granularity="1month", timezone="Europe/Oslo" + ... ) When requesting multiple time series, an easy way to get the datapoints of a specific one is to use the `.get` method on the returned ``DatapointsList`` object, then specify if you want `id` or `external_id`. Note: If you fetch a time series @@ -1128,9 +1128,12 @@ async def retrieve( ... external_id=[ ... DatapointsQuery(external_id=sensor_xid, start=ev.start_time, end=ev.end_time) ... for ev in periods - ... ]) + ... ], + ... ) >>> ts_44 = dps_lst.get(id=44) # Single ``Datapoints`` object - >>> ts_lst = dps_lst.get(external_id=sensor_xid) # List of ``len(periods)`` ``Datapoints`` objects + >>> ts_lst = dps_lst.get( + ... external_id=sensor_xid + ... ) # List of ``len(periods)`` ``Datapoints`` objects The API has an endpoint to :py:meth:`~DatapointsAPI.retrieve_latest`, i.e. "before", but not "after". Luckily, we can emulate that behaviour easily. Let's say we have a very dense time series and do not want to fetch all of the available raw data (or fetch less precise @@ -1139,10 +1142,14 @@ async def retrieve( >>> import itertools >>> month_starts = [ ... datetime(year, month, 1, tzinfo=utc) - ... for year, month in itertools.product(range(2000, 2011), range(1, 13))] + ... for year, month in itertools.product(range(2000, 2011), range(1, 13)) + ... ] >>> dps_lst = client.time_series.data.retrieve( - ... external_id=[DatapointsQuery(external_id="foo", start=start) for start in month_starts], - ... limit=1) + ... external_id=[ + ... DatapointsQuery(external_id="foo", start=start) for start in month_starts + ... ], + ... limit=1, + ... ) To get *all* historic and future datapoints for a time series, e.g. to do a backup, you may want to import the two integer constants: ``MIN_TIMESTAMP_MS`` and ``MAX_TIMESTAMP_MS``, to make sure you do not miss any. **Performance warning**: This pattern of @@ -1150,28 +1157,30 @@ async def retrieve( >>> from cognite.client.utils import MIN_TIMESTAMP_MS, MAX_TIMESTAMP_MS >>> dps_backup = client.time_series.data.retrieve( - ... id=123, - ... start=MIN_TIMESTAMP_MS, - ... end=MAX_TIMESTAMP_MS + 1) # end is exclusive + ... id=123, start=MIN_TIMESTAMP_MS, end=MAX_TIMESTAMP_MS + 1 + ... ) # end is exclusive If you have a time series with 'unit_external_id' set, you can use the 'target_unit' parameter to convert the datapoints to the desired unit. In the example below, we are converting temperature readings from a sensor measured and stored in Celsius, to Fahrenheit (we're assuming that the time series has e.g. ``unit_external_id="temperature:deg_c"`` ): >>> client.time_series.data.retrieve( - ... id=42, start="2w-ago", target_unit="temperature:deg_f") + ... id=42, start="2w-ago", target_unit="temperature:deg_f" + ... ) Or alternatively, you can use the 'target_unit_system' parameter to convert the datapoints to the desired unit system: >>> client.time_series.data.retrieve( - ... id=42, start="2w-ago", target_unit_system="Imperial") + ... id=42, start="2w-ago", target_unit_system="Imperial" + ... ) To retrieve status codes for a time series, pass ``include_status=True``. This is only possible for raw datapoint queries. You would typically also pass ``ignore_bad_datapoints=False`` to not hide all the datapoints that are marked as uncertain or bad, which is the API's default behaviour. You may also use ``treat_uncertain_as_bad`` to control how uncertain values are interpreted. >>> dps = client.time_series.data.retrieve( - ... id=42, include_status=True, ignore_bad_datapoints=False) + ... id=42, include_status=True, ignore_bad_datapoints=False + ... ) >>> dps.status_code # list of integer codes, e.g.: [0, 1073741824, 2147483648] >>> dps.status_symbol # list of symbolic representations, e.g. [Good, Uncertain, Bad] @@ -1398,7 +1407,8 @@ async def retrieve_arrays( ... id=42, ... start=datetime(2020, 1, 1, tzinfo=timezone.utc), ... aggregates=["min", "max"], - ... granularity="7d") + ... granularity="7d", + ... ) >>> weekly_range = dps.max - dps.min Get up-to 2 million raw datapoints for the last 48 hours for a noisy time series with external_id="ts-noisy", @@ -1406,9 +1416,8 @@ async def retrieve_arrays( >>> import numpy as np >>> dps = client.time_series.data.retrieve_arrays( - ... external_id="ts-noisy", - ... start="2d-ago", - ... limit=2_000_000) + ... external_id="ts-noisy", start="2d-ago", limit=2_000_000 + ... ) >>> smooth = np.convolve(dps.value, np.ones(5) / 5) # doctest: +SKIP >>> smoother = np.convolve(dps.value, np.ones(20) / 20) # doctest: +SKIP @@ -1417,10 +1426,8 @@ async def retrieve_arrays( >>> id_lst = [42, 43, 44] >>> dps_lst = client.time_series.data.retrieve_arrays( - ... id=id_lst, - ... start="2h-ago", - ... include_outside_points=True, - ... ignore_unknown_ids=True) + ... id=id_lst, start="2h-ago", include_outside_points=True, ignore_unknown_ids=True + ... ) >>> largest_gaps = [np.max(np.diff(dps.timestamp)) for dps in dps_lst] Get raw datapoints for a time series with external_id="bar" from the last 10 weeks, then convert to a ``pandas.Series`` @@ -1537,10 +1544,8 @@ async def retrieve_dataframe( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> df = client.time_series.data.retrieve_dataframe( - ... external_id="foo", - ... start="2w-ago", - ... end="now", - ... limit=100) + ... external_id="foo", start="2w-ago", end="now", limit=100 + ... ) Get the pandas dataframe with a uniform index (fixed spacing between points) of 1 day, for two time series with individually specified aggregates, from 1990 through 2020: @@ -1550,12 +1555,15 @@ async def retrieve_dataframe( >>> df = client.time_series.data.retrieve_dataframe( ... external_id=[ ... DatapointsQuery(external_id="foo", aggregates="discrete_variance"), - ... DatapointsQuery(external_id="bar", aggregates=["total_variation", "continuous_variance"]), + ... DatapointsQuery( + ... external_id="bar", aggregates=["total_variation", "continuous_variance"] + ... ), ... ], ... granularity="1d", ... start=datetime(1990, 1, 1, tzinfo=timezone.utc), ... end=datetime(2020, 12, 31, tzinfo=timezone.utc), - ... uniform_index=True) + ... uniform_index=True, + ... ) Get a pandas dataframe containing the 'average' aggregate for two time series using a monthly granularity, starting Jan 1, 1970 all the way up to present, without having the aggregate name in the columns: @@ -1564,7 +1572,8 @@ async def retrieve_dataframe( ... external_id=["foo", "bar"], ... aggregates="average", ... granularity="1mo", - ... include_aggregate_name=False) + ... include_aggregate_name=False, + ... ) You may also use ``pandas.Timestamp`` to define start and end. Here we fetch using instance_id: @@ -1572,7 +1581,8 @@ async def retrieve_dataframe( >>> df = client.time_series.data.retrieve_dataframe( ... instance_id=NodeId("my-space", "my-ts-xid"), ... start=pd.Timestamp("2023-01-01"), - ... end=pd.Timestamp("2023-02-01")) + ... end=pd.Timestamp("2023-02-01"), + ... ) """ _, pd = local_import("numpy", "pandas") # Verify that deps are available or raise CogniteImportError query = _FullDatapointsQuery( @@ -1850,8 +1860,8 @@ async def retrieve_latest( >>> from cognite.client.data_classes.data_modeling import NodeId >>> res = client.time_series.data.retrieve_latest( - ... external_id=["foo", "bar"], - ... instance_id=NodeId("my-space", "my-ts-xid")) + ... external_id=["foo", "bar"], instance_id=NodeId("my-space", "my-ts-xid") + ... ) You can also get the latest datapoint before a specific time: @@ -1869,7 +1879,9 @@ async def retrieve_latest( You may also pass an instance of LatestDatapointQuery: >>> from cognite.client.data_classes import LatestDatapointQuery - >>> res = client.time_series.data.retrieve_latest(id=LatestDatapointQuery(id=1, before=60_000)) + >>> res = client.time_series.data.retrieve_latest( + ... id=LatestDatapointQuery(id=1, before=60_000) + ... ) If you need the latest datapoint for multiple time series, simply give a list of ids. Note that we are using external ids here, but either will work: @@ -1887,16 +1899,23 @@ async def retrieve_latest( >>> id_queries = [ ... 123, ... LatestDatapointQuery(id=456, before="1w-ago"), - ... LatestDatapointQuery(id=789, before=datetime(2018,1,1, tzinfo=timezone.utc)), - ... LatestDatapointQuery(id=987, target_unit="temperature:deg_f")] + ... LatestDatapointQuery(id=789, before=datetime(2018, 1, 1, tzinfo=timezone.utc)), + ... LatestDatapointQuery(id=987, target_unit="temperature:deg_f"), + ... ] >>> ext_id_queries = [ ... "foo", - ... LatestDatapointQuery(external_id="abc", before="3h-ago", target_unit_system="Imperial"), + ... LatestDatapointQuery( + ... external_id="abc", before="3h-ago", target_unit_system="Imperial" + ... ), ... LatestDatapointQuery(external_id="def", include_status=True), ... LatestDatapointQuery(external_id="ghi", treat_uncertain_as_bad=False), - ... LatestDatapointQuery(external_id="jkl", include_status=True, ignore_bad_datapoints=False)] + ... LatestDatapointQuery( + ... external_id="jkl", include_status=True, ignore_bad_datapoints=False + ... ), + ... ] >>> res = client.time_series.data.retrieve_latest( - ... id=id_queries, external_id=ext_id_queries) + ... id=id_queries, external_id=ext_id_queries + ... ) """ fetcher = RetrieveLatestDpsFetcher( id=id, @@ -1964,10 +1983,10 @@ async def insert( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> datapoints = [ - ... (datetime(2018,1,1, tzinfo=timezone.utc), 1000), - ... (datetime(2018,1,2, tzinfo=timezone.utc), 2000, StatusCode.Good), - ... (datetime(2018,1,3, tzinfo=timezone.utc), 3000, StatusCode.Uncertain), - ... (datetime(2018,1,4, tzinfo=timezone.utc), None, StatusCode.Bad), + ... (datetime(2018, 1, 1, tzinfo=timezone.utc), 1000), + ... (datetime(2018, 1, 2, tzinfo=timezone.utc), 2000, StatusCode.Good), + ... (datetime(2018, 1, 3, tzinfo=timezone.utc), 3000, StatusCode.Uncertain), + ... (datetime(2018, 1, 4, tzinfo=timezone.utc), None, StatusCode.Bad), ... ] >>> client.time_series.data.insert(datapoints, id=1) @@ -1980,7 +1999,9 @@ async def insert( ... (160000000000, 2000, 3145728), ... (170000000000, 2000, 2147483648), # Same as StatusCode.Bad ... ] - >>> client.time_series.data.insert(datapoints, instance_id=NodeId("my-space", "my-ts-xid")) + >>> client.time_series.data.insert( + ... datapoints, instance_id=NodeId("my-space", "my-ts-xid") + ... ) Or they can be a list of dictionaries: @@ -1990,7 +2011,11 @@ async def insert( ... {"timestamp": 160000000000, "value": 2000}, ... {"timestamp": 170000000000, "value": 3000, "status": {"code": 0}}, ... {"timestamp": 180000000000, "value": 4000, "status": {"symbol": "Uncertain"}}, - ... {"timestamp": 190000000000, "value": math.nan, "status": {"code": StatusCode.Bad, "symbol": "Bad"}}, + ... { + ... "timestamp": 190000000000, + ... "value": math.nan, + ... "status": {"code": StatusCode.Bad, "symbol": "Bad"}, + ... }, ... ] >>> client.time_series.data.insert(datapoints, external_id="abcd") @@ -2053,35 +2078,61 @@ async def insert_multiple( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> to_insert = [ - ... {"id": 1, "datapoints": [ - ... (datetime(2018,1,1, tzinfo=timezone.utc), 1000), - ... (datetime(2018,1,2, tzinfo=timezone.utc), 2000, StatusCode.Good)], + ... { + ... "id": 1, + ... "datapoints": [ + ... (datetime(2018, 1, 1, tzinfo=timezone.utc), 1000), + ... (datetime(2018, 1, 2, tzinfo=timezone.utc), 2000, StatusCode.Good), + ... ], ... }, - ... {"external_id": "foo", "datapoints": [ - ... (datetime(2018,1,3, tzinfo=timezone.utc), 3000), - ... (datetime(2018,1,4, tzinfo=timezone.utc), 4000, StatusCode.Uncertain)], + ... { + ... "external_id": "foo", + ... "datapoints": [ + ... (datetime(2018, 1, 3, tzinfo=timezone.utc), 3000), + ... (datetime(2018, 1, 4, tzinfo=timezone.utc), 4000, StatusCode.Uncertain), + ... ], + ... }, + ... { + ... "instance_id": NodeId("my-space", "my-ts-xid"), + ... "datapoints": [ + ... (datetime(2018, 1, 5, tzinfo=timezone.utc), 5000), + ... (datetime(2018, 1, 6, tzinfo=timezone.utc), None, StatusCode.Bad), + ... ], ... }, - ... {"instance_id": NodeId("my-space", "my-ts-xid"), "datapoints": [ - ... (datetime(2018,1,5, tzinfo=timezone.utc), 5000), - ... (datetime(2018,1,6, tzinfo=timezone.utc), None, StatusCode.Bad)], - ... } ... ] Passing datapoints using the dictionary format with timestamp given in milliseconds since epoch: >>> import math >>> to_insert.append( - ... {"external_id": "bar", "datapoints": [ - ... {"timestamp": 170000000, "value": 7000}, - ... {"timestamp": 180000000, "value": 8000, "status": {"symbol": "Uncertain"}}, - ... {"timestamp": 190000000, "value": None, "status": {"code": StatusCode.Bad}}, - ... {"timestamp": 200000000, "value": math.inf, "status": {"code": StatusCode.Bad, "symbol": "Bad"}}, - ... ]}) + ... { + ... "external_id": "bar", + ... "datapoints": [ + ... {"timestamp": 170000000, "value": 7000}, + ... { + ... "timestamp": 180000000, + ... "value": 8000, + ... "status": {"symbol": "Uncertain"}, + ... }, + ... { + ... "timestamp": 190000000, + ... "value": None, + ... "status": {"code": StatusCode.Bad}, + ... }, + ... { + ... "timestamp": 200000000, + ... "value": math.inf, + ... "status": {"code": StatusCode.Bad, "symbol": "Bad"}, + ... }, + ... ], + ... } + ... ) If the Datapoints or DatapointsArray are fetched with status codes, these will be automatically used in the insert: >>> data_to_clone = client.time_series.data.retrieve( - ... external_id="bar", include_status=True, ignore_bad_datapoints=False) + ... external_id="bar", include_status=True, ignore_bad_datapoints=False + ... ) >>> to_insert.append({"external_id": "bar-clone", "datapoints": data_to_clone}) >>> client.time_series.data.insert_multiple(to_insert) """ @@ -2141,8 +2192,10 @@ async def delete_ranges(self, ranges: list[dict[str, Any]]) -> None: >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> ranges = [{"id": 1, "start": "2d-ago", "end": "now"}, - ... {"external_id": "abc", "start": "2d-ago", "end": "2d-ahead"}] + >>> ranges = [ + ... {"id": 1, "start": "2d-ago", "end": "now"}, + ... {"external_id": "abc", "start": "2d-ago", "end": "2d-ahead"}, + ... ] >>> client.time_series.data.delete_ranges(ranges) """ valid_ranges = [] @@ -2198,7 +2251,7 @@ async def insert_dataframe(self, df: pd.DataFrame, dropna: bool = True) -> None: ... "foo": np.random.normal(0, 1, 100), ... node_id: np.random.normal(0, 1, 100), ... }, - ... index=pd.date_range(start="2018-01-01", periods=100, freq="1d") + ... index=pd.date_range(start="2018-01-01", periods=100, freq="1d"), ... ) >>> client.time_series.data.insert_dataframe(df) """ diff --git a/cognite/client/_api/datapoints_subscriptions.py b/cognite/client/_api/datapoints_subscriptions.py index b1d7f6eaa4..8e4d3a38ee 100644 --- a/cognite/client/_api/datapoints_subscriptions.py +++ b/cognite/client/_api/datapoints_subscriptions.py @@ -88,7 +88,8 @@ async def create(self, subscription: DataPointSubscriptionWrite) -> DatapointSub ... external_id="my_subscription", ... name="My subscription", ... partition_count=1, - ... time_series_ids=["myFistTimeSeries", "mySecondTimeSeries"]) + ... time_series_ids=["myFistTimeSeries", "mySecondTimeSeries"], + ... ) >>> created = client.time_series.subscriptions.create(sub) Create a subscription with explicit time series IDs given as Node IDs @@ -100,22 +101,30 @@ async def create(self, subscription: DataPointSubscriptionWrite) -> DatapointSub ... external_id="my_subscription", ... name="My subscription with Data Model Ids", ... partition_count=1, - ... instance_ids=[NodeId("my_space", "myFistTimeSeries"), NodeId("my_space", "mySecondTimeSeries")]) + ... instance_ids=[ + ... NodeId("my_space", "myFistTimeSeries"), + ... NodeId("my_space", "mySecondTimeSeries"), + ... ], + ... ) >>> created = client.time_series.subscriptions.create(sub) Create a filter defined subscription for all numeric time series that are stepwise: >>> from cognite.client.data_classes import DataPointSubscriptionWrite >>> from cognite.client.data_classes import filters as flt - >>> from cognite.client.data_classes.datapoints_subscriptions import DatapointSubscriptionProperty + >>> from cognite.client.data_classes.datapoints_subscriptions import ( + ... DatapointSubscriptionProperty, + ... ) >>> is_numeric_stepwise = flt.And( ... flt.Equals(DatapointSubscriptionProperty.is_string, False), - ... flt.Equals(DatapointSubscriptionProperty.is_step, True)) + ... flt.Equals(DatapointSubscriptionProperty.is_step, True), + ... ) >>> sub = DataPointSubscriptionWrite( ... external_id="my_subscription", ... name="My subscription for numeric, stepwise time series", ... partition_count=1, - ... filter=is_numeric_stepwise) + ... filter=is_numeric_stepwise, + ... ) >>> created = client.time_series.subscriptions.create(sub) """ @@ -245,7 +254,9 @@ async def update( Add a time series to a preexisting subscription: >>> from cognite.client.data_classes import DataPointSubscriptionUpdate - >>> update = DataPointSubscriptionUpdate("my_subscription").time_series_ids.add(["MyNewTimeSeriesExternalId"]) + >>> update = DataPointSubscriptionUpdate("my_subscription").time_series_ids.add( + ... ["MyNewTimeSeriesExternalId"] + ... ) >>> updated = client.time_series.subscriptions.update(update) """ @@ -314,7 +325,9 @@ async def iterate_data( Iterate continuously over all changes to the subscription newer than 3 days: - >>> for batch in client.time_series.subscriptions.iterate_data("my_subscription", "3d-ago"): + >>> for batch in client.time_series.subscriptions.iterate_data( + ... "my_subscription", "3d-ago" + ... ): ... pass # do something """ current_partitions = [DatapointSubscriptionPartition(partition, cursor)] diff --git a/cognite/client/_api/diagrams.py b/cognite/client/_api/diagrams.py index 290ce96ae8..d890c7c519 100644 --- a/cognite/client/_api/diagrams.py +++ b/cognite/client/_api/diagrams.py @@ -161,8 +161,9 @@ async def detect( >>> # async_client = AsyncCogniteClient() # another option >>> detect_job = client.diagrams.detect( ... entities=[ - ... {"userDefinedField": "21PT1017","ignoredField": "AA11"}, - ... {"userDefinedField": "21PT1018"}], + ... {"userDefinedField": "21PT1017", "ignoredField": "AA11"}, + ... {"userDefinedField": "21PT1018"}, + ... ], ... search_field="userDefinedField", ... partial_match=True, ... min_tokens=2, @@ -170,8 +171,9 @@ async def detect( ... file_external_ids=["Test1"], ... file_references=[ ... FileReference(id=20, first_page=1, last_page=10), - ... FileReference(external_id="ext_20", first_page=11, last_page=20) - ... ]) + ... FileReference(external_id="ext_20", first_page=11, last_page=20), + ... ], + ... ) >>> result = detect_job.get_result() >>> print(result) @@ -207,13 +209,16 @@ async def detect( To use beta configuration options you can use a dictionary or `DiagramDetectConfig` object for convenience: - >>> from cognite.client.data_classes.contextualization import ConnectionFlags, DiagramDetectConfig + >>> from cognite.client.data_classes.contextualization import ( + ... ConnectionFlags, + ... DiagramDetectConfig, + ... ) >>> config = DiagramDetectConfig( ... remove_leading_zeros=True, ... connection_flags=ConnectionFlags( ... no_text_inbetween=True, ... natural_reading_order=True, - ... ) + ... ), ... ) >>> job = client.diagrams.detect(entities=[{"name": "A1"}], file_id=123, config=config) diff --git a/cognite/client/_api/document_preview.py b/cognite/client/_api/document_preview.py index 54aa6c9700..0d57ce197b 100644 --- a/cognite/client/_api/document_preview.py +++ b/cognite/client/_api/document_preview.py @@ -32,7 +32,9 @@ async def download_page_as_png_bytes(self, id: int, page_number: int = 1) -> byt Download an image preview and display using IPython.display.Image (for example in a Jupyter Notebook): >>> from IPython.display import Image - >>> binary_png = client.documents.previews.download_page_as_png_bytes(id=123, page_number=5) + >>> binary_png = client.documents.previews.download_page_as_png_bytes( + ... id=123, page_number=5 + ... ) >>> Image(binary_png) """ response = await self._get( diff --git a/cognite/client/_api/documents.py b/cognite/client/_api/documents.py index 820fcda120..2c6c80dca1 100644 --- a/cognite/client/_api/documents.py +++ b/cognite/client/_api/documents.py @@ -118,7 +118,7 @@ async def aggregate_count(self, query: str | None = None, filter: Filter | dict[ >>> client.documents.aggregate_count( ... filter=filters.InAssetSubtree( ... property=DocumentProperty.asset_external_ids, - ... values=['Plant_1', 'Plant_2'], + ... values=["Plant_1", "Plant_2"], ... ) ... ) """ @@ -160,7 +160,9 @@ async def aggregate_cardinality_values( >>> from cognite.client.data_classes import filters >>> from cognite.client.data_classes.documents import DocumentProperty >>> is_plain_text = filters.Equals(DocumentProperty.mime_type, "text/plain") - >>> plain_text_author_count = client.documents.aggregate_cardinality_values(DocumentProperty.author, filter=is_plain_text) + >>> plain_text_author_count = client.documents.aggregate_cardinality_values( + ... DocumentProperty.author, filter=is_plain_text + ... ) Count the number of types of documents in your CDF project but exclude documents that start with "text": @@ -168,7 +170,9 @@ async def aggregate_cardinality_values( >>> from cognite.client.data_classes import aggregations >>> agg = aggregations >>> is_not_text = agg.Not(agg.Prefix("text")) - >>> type_count_excluded_text = client.documents.aggregate_cardinality_values(DocumentProperty.type, aggregate_filter=is_not_text) + >>> type_count_excluded_text = client.documents.aggregate_cardinality_values( + ... DocumentProperty.type, aggregate_filter=is_not_text + ... ) """ self._validate_filter(filter) @@ -253,7 +257,9 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes import filters >>> from cognite.client.data_classes.documents import DocumentProperty >>> is_abc = filters.Prefix(DocumentProperty.external_id, "abc") - >>> result = client.documents.aggregate_unique_values(DocumentProperty.language, filter=is_abc) + >>> result = client.documents.aggregate_unique_values( + ... DocumentProperty.language, filter=is_abc + ... ) >>> unique_languages = result.unique Get the unique mime types with count of documents, but exclude mime types that start with text: @@ -262,7 +268,9 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes import aggregations >>> agg = aggregations >>> is_not_text = agg.Not(agg.Prefix("text")) - >>> result = client.documents.aggregate_unique_values(DocumentProperty.mime_type, aggregate_filter=is_not_text) + >>> result = client.documents.aggregate_unique_values( + ... DocumentProperty.mime_type, aggregate_filter=is_not_text + ... ) >>> unique_mime_types = result.unique """ self._validate_filter(filter) @@ -486,11 +494,15 @@ async def search( >>> from cognite.client.data_classes.documents import DocumentProperty >>> from cognite.client.utils import timestamp_to_ms >>> is_plain_text = filters.Equals(DocumentProperty.mime_type, "text/plain") - >>> last_week = filters.Range(DocumentProperty.created_time, - ... gt=timestamp_to_ms(datetime.now() - timedelta(days=7))) - >>> documents = client.documents.search('"CPLEX Error 1217: No Solution exists."', + >>> last_week = filters.Range( + ... DocumentProperty.created_time, + ... gt=timestamp_to_ms(datetime.now() - timedelta(days=7)), + ... ) + >>> documents = client.documents.search( + ... '"CPLEX Error 1217: No Solution exists."', ... highlight=True, - ... filter=filters.And(is_plain_text, last_week)) + ... filter=filters.And(is_plain_text, last_week), + ... ) """ self._validate_filter(filter) body: dict[str, str | int | bool | dict | list] = {"search": {"query": query}} diff --git a/cognite/client/_api/entity_matching.py b/cognite/client/_api/entity_matching.py index 159c570ab6..c8050a7086 100644 --- a/cognite/client/_api/entity_matching.py +++ b/cognite/client/_api/entity_matching.py @@ -63,7 +63,7 @@ async def retrieve_multiple( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> retrieved_models = client.entity_matching.retrieve_multiple([1,2,3]) + >>> retrieved_models = client.entity_matching.retrieve_multiple([1, 2, 3]) """ identifiers = IdentifierSequence.load(ids=ids, external_ids=external_ids) @@ -223,14 +223,16 @@ async def fit( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> sources = [{'id': 101, 'name': 'ChildAsset1', 'description': 'Child of ParentAsset1'}] - >>> targets = [{'id': 1, 'name': 'ParentAsset1', 'description': 'Parent to ChildAsset1'}] + >>> sources = [ + ... {"id": 101, "name": "ChildAsset1", "description": "Child of ParentAsset1"} + ... ] + >>> targets = [{"id": 1, "name": "ParentAsset1", "description": "Parent to ChildAsset1"}] >>> true_matches = [(1, 101)] >>> model = client.entity_matching.fit( ... sources=sources, ... targets=targets, ... true_matches=true_matches, - ... description="AssetMatchingJob1" + ... description="AssetMatchingJob1", ... ) """ @@ -293,15 +295,11 @@ async def predict( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> sources = {'id': 101, 'name': 'ChildAsset1', 'description': 'Child of ParentAsset1'} - >>> targets = {'id': 1, 'name': 'ParentAsset1', 'description': 'Parent to ChildAsset1'} + >>> sources = {"id": 101, "name": "ChildAsset1", "description": "Child of ParentAsset1"} + >>> targets = {"id": 1, "name": "ParentAsset1", "description": "Parent to ChildAsset1"} >>> true_matches = [(1, 101)] >>> model = client.entity_matching.predict( - ... sources = sources, - ... targets = targets, - ... num_matches = 1, - ... score_threshold = 0.6, - ... id=1 + ... sources=sources, targets=targets, num_matches=1, score_threshold=0.6, id=1 ... ) """ model = await self._get_model_or_raise(id, external_id) @@ -344,8 +342,10 @@ async def refit( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> sources = [{'id': 101, 'name': 'ChildAsset1', 'description': 'Child of ParentAsset1'}] - >>> targets = [{'id': 1, 'name': 'ParentAsset1', 'description': 'Parent to ChildAsset1'}] + >>> sources = [ + ... {"id": 101, "name": "ChildAsset1", "description": "Child of ParentAsset1"} + ... ] + >>> targets = [{"id": 1, "name": "ParentAsset1", "description": "Parent to ChildAsset1"}] >>> true_matches = [(1, 101)] >>> model = client.entity_matching.refit(true_matches=true_matches, id=1) """ diff --git a/cognite/client/_api/events.py b/cognite/client/_api/events.py index bb5d870979..086fa038cf 100644 --- a/cognite/client/_api/events.py +++ b/cognite/client/_api/events.py @@ -267,8 +267,12 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes.events import EventProperty >>> from cognite.client.utils import timestamp_to_ms >>> from datetime import datetime - >>> is_after_2020 = filters.Range(EventProperty.start_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.events.aggregate_unique_values(EventProperty.type, advanced_filter=is_after_2020) + >>> is_after_2020 = filters.Range( + ... EventProperty.start_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.events.aggregate_unique_values( + ... EventProperty.type, advanced_filter=is_after_2020 + ... ) >>> print(result.unique) Get the unique types of events after 2020-01-01 in your CDF project, but exclude all types that start with @@ -278,8 +282,12 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes import aggregations >>> agg = aggregations >>> not_planned = agg.Not(agg.Prefix("planned")) - >>> is_after_2020 = filters.Range(EventProperty.start_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.events.aggregate_unique_values(EventProperty.type, advanced_filter=is_after_2020, aggregate_filter=not_planned) + >>> is_after_2020 = filters.Range( + ... EventProperty.start_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.events.aggregate_unique_values( + ... EventProperty.type, advanced_filter=is_after_2020, aggregate_filter=not_planned + ... ) >>> print(result.unique) """ @@ -365,7 +373,9 @@ async def aggregate_cardinality_values( >>> from cognite.client.data_classes import filters >>> from cognite.client.data_classes.events import EventProperty >>> is_asset = filters.ContainsAny(EventProperty.asset_ids, 123) - >>> plain_text_author_count = client.events.aggregate_cardinality_values(EventProperty.type, advanced_filter=is_asset) + >>> plain_text_author_count = client.events.aggregate_cardinality_values( + ... EventProperty.type, advanced_filter=is_asset + ... ) """ self._validate_filter(advanced_filter) @@ -505,7 +515,7 @@ async def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.events.delete(id=[1,2,3], external_id="3") + >>> client.events.delete(id=[1, 2, 3], external_id="3") """ await self._delete_multiple( identifiers=IdentifierSequence.load(ids=id, external_ids=external_id), @@ -555,7 +565,11 @@ async def update( Perform a partial update on a event, updating the description and adding a new field to metadata: >>> from cognite.client.data_classes import EventUpdate - >>> my_update = EventUpdate(id=1).description.set("New description").metadata.add({"key": "value"}) + >>> my_update = ( + ... EventUpdate(id=1) + ... .description.set("New description") + ... .metadata.add({"key": "value"}) + ... ) >>> res = client.events.update(my_update) """ return await self._update_multiple( @@ -715,7 +729,7 @@ async def list( Iterate over chunks of events to reduce memory load: >>> for event_list in client.events(chunk_size=2500): - ... event_list # do something with the events + ... event_list # do something with the events Using advanced filter, find all events that have a metadata key 'timezone' starting with 'Europe', and sort by external id ascending: @@ -734,17 +748,19 @@ async def list( >>> from cognite.client.data_classes.events import EventProperty, SortableEventProperty >>> in_timezone = filters.Prefix(EventProperty.metadata_key("timezone"), "Europe") >>> res = client.events.list( - ... advanced_filter=in_timezone, - ... sort=(SortableEventProperty.external_id, "asc")) + ... advanced_filter=in_timezone, sort=(SortableEventProperty.external_id, "asc") + ... ) Combine filter and advanced filter: >>> from cognite.client.data_classes import filters >>> not_instrument_lvl5 = filters.And( - ... filters.ContainsAny("labels", ["Level5"]), - ... filters.Not(filters.ContainsAny("labels", ["Instrument"])) + ... filters.ContainsAny("labels", ["Level5"]), + ... filters.Not(filters.ContainsAny("labels", ["Instrument"])), + ... ) + >>> res = client.events.list( + ... asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5 ... ) - >>> res = client.events.list(asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5) """ asset_subtree_ids_processed = process_asset_subtree_ids(asset_subtree_ids, asset_subtree_external_ids) diff --git a/cognite/client/_api/extractionpipelines/__init__.py b/cognite/client/_api/extractionpipelines/__init__.py index 06bac1988b..c86c6ecffe 100644 --- a/cognite/client/_api/extractionpipelines/__init__.py +++ b/cognite/client/_api/extractionpipelines/__init__.py @@ -119,7 +119,9 @@ async def retrieve_multiple( Get assets by external id: - >>> res = client.extraction_pipelines.retrieve_multiple(external_ids=["abc", "def"], ignore_unknown_ids=True) + >>> res = client.extraction_pipelines.retrieve_multiple( + ... external_ids=["abc", "def"], ignore_unknown_ids=True + ... ) """ identifiers = IdentifierSequence.load(ids=ids, external_ids=external_ids) return await self._retrieve_multiple( @@ -213,7 +215,7 @@ async def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.extraction_pipelines.delete(id=[1,2,3], external_id="3") + >>> client.extraction_pipelines.delete(id=[1, 2, 3], external_id="3") """ await self._delete_multiple( identifiers=IdentifierSequence.load(id, external_id), wrap_ids=True, extra_body_fields={} diff --git a/cognite/client/_api/extractionpipelines/configs.py b/cognite/client/_api/extractionpipelines/configs.py index dc81fa81fa..eb775ce91f 100644 --- a/cognite/client/_api/extractionpipelines/configs.py +++ b/cognite/client/_api/extractionpipelines/configs.py @@ -86,7 +86,9 @@ async def create( >>> from cognite.client import CogniteClient >>> from cognite.client.data_classes import ExtractionPipelineConfigWrite >>> client = CogniteClient() - >>> res = client.extraction_pipelines.config.create(ExtractionPipelineConfigWrite(external_id="extId", config="my config contents")) + >>> res = client.extraction_pipelines.config.create( + ... ExtractionPipelineConfigWrite(external_id="extId", config="my config contents") + ... ) """ if isinstance(config, ExtractionPipelineConfig): config = config.as_write() diff --git a/cognite/client/_api/extractionpipelines/runs.py b/cognite/client/_api/extractionpipelines/runs.py index 2523bb680d..26a2256039 100644 --- a/cognite/client/_api/extractionpipelines/runs.py +++ b/cognite/client/_api/extractionpipelines/runs.py @@ -63,12 +63,16 @@ async def list( Filter extraction pipeline runs on a given status: - >>> runs_list = client.extraction_pipelines.runs.list(external_id="test ext id", statuses=["seen"], limit=5) + >>> runs_list = client.extraction_pipelines.runs.list( + ... external_id="test ext id", statuses=["seen"], limit=5 + ... ) Get all failed pipeline runs in the last 24 hours for pipeline 'extId': >>> from cognite.client.data_classes import ExtractionPipelineRun - >>> res = client.extraction_pipelines.runs.list(external_id="extId", statuses="failure", created_time="24h-ago") + >>> res = client.extraction_pipelines.runs.list( + ... external_id="extId", statuses="failure", created_time="24h-ago" + ... ) """ if isinstance(created_time, str): created_time = TimestampRange(min=timestamp_to_ms(created_time)) @@ -129,7 +133,8 @@ async def create( >>> from cognite.client.data_classes import ExtractionPipelineRunWrite >>> client = CogniteClient() >>> res = client.extraction_pipelines.runs.create( - ... ExtractionPipelineRunWrite(status="success", extpipe_external_id="extId")) + ... ExtractionPipelineRunWrite(status="success", extpipe_external_id="extId") + ... ) """ assert_type(run, "run", [ExtractionPipelineRunCore, Sequence]) return await self._create_multiple( diff --git a/cognite/client/_api/files.py b/cognite/client/_api/files.py index 2395c64383..f305963b3c 100644 --- a/cognite/client/_api/files.py +++ b/cognite/client/_api/files.py @@ -327,7 +327,7 @@ async def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.files.delete(id=[1,2,3], external_id="3") + >>> client.files.delete(id=[1, 2, 3], external_id="3") """ await self._delete_multiple( identifiers=IdentifierSequence.load(ids=id, external_ids=external_id), @@ -381,7 +381,9 @@ async def update( Perform a partial update on file metadata, updating the source and adding a new field to metadata: >>> from cognite.client.data_classes import FileMetadataUpdate - >>> my_update = FileMetadataUpdate(id=1).source.set("new source").metadata.add({"key": "value"}) + >>> my_update = ( + ... FileMetadataUpdate(id=1).source.set("new source").metadata.add({"key": "value"}) + ... ) >>> res = client.files.update(my_update) Attach labels to a files: @@ -434,7 +436,9 @@ async def search( Search for an asset with an attached label: >>> my_label_filter = LabelFilter(contains_all=["WELL LOG"]) - >>> res = client.assets.search(name="xyz",filter=FileMetadataFilter(labels=my_label_filter)) + >>> res = client.assets.search( + ... name="xyz", filter=FileMetadataFilter(labels=my_label_filter) + ... ) """ return await self._search(list_cls=FileMetadataList, search={"name": name}, filter=filter or {}, limit=limit) @@ -531,13 +535,17 @@ async def upload( Upload a file with a label: >>> from cognite.client.data_classes import Label - >>> res = client.files.upload(my_file, name="my_file", labels=[Label(external_id="WELL LOG")]) + >>> res = client.files.upload( + ... my_file, name="my_file", labels=[Label(external_id="WELL LOG")] + ... ) Upload a file with a geo_location: >>> from cognite.client.data_classes import GeoLocation, Geometry >>> geometry = Geometry(type="LineString", coordinates=[[30, 10], [10, 30], [40, 40]]) - >>> res = client.files.upload(my_file, geo_location=GeoLocation(type="Feature", geometry=geometry)) + >>> res = client.files.upload( + ... my_file, geo_location=GeoLocation(type="Feature", geometry=geometry) + ... ) """ file_metadata = FileMetadataWrite( @@ -608,14 +616,14 @@ async def upload_content_bytes( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.files.upload_content_bytes( - ... b"some content", external_id="my_file_xid") + >>> res = client.files.upload_content_bytes(b"some content", external_id="my_file_xid") ...or by using instance_id: >>> from cognite.client.data_classes.data_modeling import NodeId >>> res = client.files.upload_content_bytes( - ... b"some content", instance_id=NodeId("my-space", "my_file_xid")) + ... b"some content", instance_id=NodeId("my-space", "my_file_xid") + ... ) """ identifiers = IdentifierSequence.load(external_ids=external_id, instance_ids=instance_id).as_singleton() @@ -719,7 +727,7 @@ async def upload_bytes( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.files.upload_bytes(b"some content", name="my_file", asset_ids=[1,2,3]) + >>> res = client.files.upload_bytes(b"some content", name="my_file", asset_ids=[1, 2, 3]) """ file_metadata = FileMetadataWrite( name=name, @@ -892,7 +900,9 @@ async def multipart_upload_content_session( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> with client.files.multipart_upload_content_session(external_id="external-id", parts=2) as session: + >>> with client.files.multipart_upload_content_session( + ... external_id="external-id", parts=2 + ... ) as session: ... # Note that the minimum chunk size is 5 MiB. ... session.upload_part(0, "hello" * 1_200_000) ... session.upload_part(1, " world") @@ -1067,11 +1077,13 @@ async def download( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.files.download(directory="my_directory", id=[1,2,3], external_id=["abc", "def"]) + >>> client.files.download( + ... directory="my_directory", id=[1, 2, 3], external_id=["abc", "def"] + ... ) Download files by id to the current directory: - >>> client.files.download(directory=".", id=[1,2,3]) + >>> client.files.download(directory=".", id=[1, 2, 3]) """ identifiers = IdentifierSequence.load(ids=id, external_ids=external_id, instance_ids=instance_id) @@ -1324,7 +1336,7 @@ async def list( Iterate over chunks of files metadata to reduce memory load: >>> for file_list in client.files(chunk_size=2500): - ... file_list # do something with the files + ... file_list # do something with the files Filter files based on labels: @@ -1335,7 +1347,9 @@ async def list( Filter files based on geoLocation: >>> from cognite.client.data_classes import GeoLocationFilter, GeometryFilter - >>> my_geo_location_filter = GeoLocationFilter(relation="intersects", shape=GeometryFilter(type="Point", coordinates=[35,10])) + >>> my_geo_location_filter = GeoLocationFilter( + ... relation="intersects", shape=GeometryFilter(type="Point", coordinates=[35, 10]) + ... ) >>> file_list = client.files.list(geo_location=my_geo_location_filter) """ asset_subtree_ids_processed = process_asset_subtree_ids(asset_subtree_ids, asset_subtree_external_ids) diff --git a/cognite/client/_api/functions/__init__.py b/cognite/client/_api/functions/__init__.py index 96627846ae..66cb2667c5 100644 --- a/cognite/client/_api/functions/__init__.py +++ b/cognite/client/_api/functions/__init__.py @@ -216,14 +216,14 @@ async def create( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> function = client.functions.create( - ... name="myfunction", - ... folder="path/to/code", - ... function_path="path/to/function.py") + ... name="myfunction", folder="path/to/code", function_path="path/to/function.py" + ... ) Create function with file_id from already uploaded source code: >>> function = client.functions.create( - ... name="myfunction", file_id=123, function_path="path/to/function.py") + ... name="myfunction", file_id=123, function_path="path/to/function.py" + ... ) Create function with predefined function object named `handle`: diff --git a/cognite/client/_api/functions/schedules.py b/cognite/client/_api/functions/schedules.py index cfabebe6b8..a9c9503aaa 100644 --- a/cognite/client/_api/functions/schedules.py +++ b/cognite/client/_api/functions/schedules.py @@ -238,7 +238,9 @@ async def create( ... name="My schedule", ... function_id=123, ... cron_expression="*/5 * * * *", - ... client_credentials=ClientCredentials("my-client-id", os.environ["MY_CLIENT_SECRET"]), + ... client_credentials=ClientCredentials( + ... "my-client-id", os.environ["MY_CLIENT_SECRET"] + ... ), ... description="This schedule does magic stuff.", ... data={"magic": "stuff"}, ... ) @@ -265,7 +267,7 @@ async def create( ... function_id=456, ... cron_expression="*/5 * * * *", ... description="A schedule just used for some temporary testing.", - ... nonce=session.nonce + ... nonce=session.nonce, ... ), ... ) @@ -324,7 +326,7 @@ async def delete(self, id: int) -> None: >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.functions.schedules.delete(id = 123) + >>> client.functions.schedules.delete(id=123) """ url = f"{self._RESOURCE_PATH}/delete" diff --git a/cognite/client/_api/geospatial.py b/cognite/client/_api/geospatial.py index 1e25fe3713..ba8526e348 100644 --- a/cognite/client/_api/geospatial.py +++ b/cognite/client/_api/geospatial.py @@ -135,7 +135,7 @@ async def list_feature_types(self) -> FeatureTypeList: >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> for feature_type in client.geospatial.list_feature_types(): - ... feature_type # do something with the feature type definition + ... feature_type # do something with the feature type definition """ return await self._list( list_cls=FeatureTypeList, @@ -196,26 +196,29 @@ async def patch_feature_types(self, patch: FeatureTypePatch | Sequence[FeatureTy >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> res = client.geospatial.patch_feature_types( - ... patch=FeatureTypePatch( - ... external_id="wells", - ... property_patches=Patches(add={"altitude": {"type": "DOUBLE"}}), - ... search_spec_patches=Patches( - ... add={ - ... "altitude_idx": {"properties": ["altitude"]}, - ... "composite_idx": {"properties": ["location", "altitude"]} - ... } - ... ) - ... ) + ... patch=FeatureTypePatch( + ... external_id="wells", + ... property_patches=Patches(add={"altitude": {"type": "DOUBLE"}}), + ... search_spec_patches=Patches( + ... add={ + ... "altitude_idx": {"properties": ["altitude"]}, + ... "composite_idx": {"properties": ["location", "altitude"]}, + ... } + ... ), + ... ) ... ) Add an additional index to an existing property >>> from cognite.client.data_classes.geospatial import Patches >>> res = client.geospatial.patch_feature_types( - ... patch=FeatureTypePatch( + ... patch=FeatureTypePatch( ... external_id="wells", - ... search_spec_patches=Patches(add={"location_idx": {"properties": ["location"]}}) - ... )) + ... search_spec_patches=Patches( + ... add={"location_idx": {"properties": ["location"]}} + ... ), + ... ) + ... ) """ if isinstance(patch, FeatureTypePatch): @@ -284,18 +287,16 @@ async def create_features( ... external_id="my_feature_type", ... properties={ ... "location": {"type": "POINT", "srid": 4326}, - ... "temperature": {"type": "DOUBLE"} - ... } + ... "temperature": {"type": "DOUBLE"}, + ... }, ... ) ... ] >>> res = client.geospatial.create_feature_types(feature_types) >>> res = client.geospatial.create_features( ... feature_type_external_id="my_feature_type", ... feature=FeatureWrite( - ... external_id="my_feature", - ... location={"wkt": "POINT(1 1)"}, - ... temperature=12.4 - ... ) + ... external_id="my_feature", location={"wkt": "POINT(1 1)"}, temperature=12.4 + ... ), ... ) """ if chunk_size is not None and (chunk_size < 1 or chunk_size > self._CREATE_LIMIT): @@ -333,8 +334,7 @@ async def delete_features( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> client.geospatial.delete_features( - ... feature_type_external_id="my_feature_type", - ... external_id=my_feature + ... feature_type_external_id="my_feature_type", external_id=my_feature ... ) """ resource_path = self._feature_resource_path(feature_type_external_id) @@ -383,8 +383,7 @@ async def retrieve_features( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> client.geospatial.retrieve_features( - ... feature_type_external_id="my_feature_type", - ... external_id="my_feature" + ... feature_type_external_id="my_feature_type", external_id="my_feature" ... ) """ resource_path = self._feature_resource_path(feature_type_external_id) @@ -443,11 +442,11 @@ async def update_features( >>> # async_client = AsyncCogniteClient() # another option >>> my_feature = client.geospatial.create_features( ... feature_type_external_id="my_feature_type", - ... feature=Feature(external_id="my_feature", temperature=12.4) + ... feature=Feature(external_id="my_feature", temperature=12.4), ... ) >>> my_updated_feature = client.geospatial.update_features( ... feature_type_external_id="my_feature_type", - ... feature=Feature(external_id="my_feature", temperature=6.237) + ... feature=Feature(external_id="my_feature", temperature=6.237), ... ) """ if chunk_size is not None and (chunk_size < 1 or chunk_size > self._UPDATE_LIMIT): @@ -503,14 +502,12 @@ async def list_features( >>> my_feature = client.geospatial.create_features( ... feature_type_external_id=my_feature_type, ... feature=Feature( - ... external_id="my_feature", - ... temperature=12.4, - ... location={"wkt": "POINT(0 1)"} - ... ) + ... external_id="my_feature", temperature=12.4, location={"wkt": "POINT(0 1)"} + ... ), ... ) >>> res = client.geospatial.list_features( ... feature_type_external_id="my_feature_type", - ... filter={"range": {"property": "temperature", "gt": 12.0}} + ... filter={"range": {"property": "temperature", "gt": 12.0}}, ... ) >>> for f in res: ... # do something with the features @@ -520,17 +517,19 @@ async def list_features( >>> res = client.geospatial.list_features( ... feature_type_external_id=my_feature_type, ... filter={}, - ... properties={"temperature": {}, "pressure": {}} + ... properties={"temperature": {}, "pressure": {}}, ... ) Search for features with spatial filters: >>> res = client.geospatial.list_features( ... feature_type_external_id=my_feature_type, - ... filter={"stWithin": { - ... "property": "location", - ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"} - ... }} + ... filter={ + ... "stWithin": { + ... "property": "location", + ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"}, + ... } + ... }, ... ) """ return await self._list( @@ -588,14 +587,12 @@ async def search_features( >>> my_feature = client.geospatial.create_features( ... feature_type_external_id=my_feature_type, ... feature=Feature( - ... external_id="my_feature", - ... temperature=12.4, - ... location={"wkt": "POINT(0 1)"} - ... ) + ... external_id="my_feature", temperature=12.4, location={"wkt": "POINT(0 1)"} + ... ), ... ) >>> res = client.geospatial.search_features( ... feature_type_external_id="my_feature_type", - ... filter={"range": {"property": "temperature", "gt": 12.0}} + ... filter={"range": {"property": "temperature", "gt": 12.0}}, ... ) >>> for f in res: ... # do something with the features @@ -605,7 +602,7 @@ async def search_features( >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, ... filter={}, - ... properties={"temperature": {}, "pressure": {}} + ... properties={"temperature": {}, "pressure": {}}, ... ) Search for features and do CRS conversion on an output property: @@ -613,7 +610,7 @@ async def search_features( >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, ... filter={}, - ... properties={"location": {"srid": 3995}} + ... properties={"location": {"srid": 3995}}, ... ) Search for features and order results: @@ -621,43 +618,51 @@ async def search_features( >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, ... filter={}, - ... order_by=[ - ... OrderSpec("temperature", "ASC"), - ... OrderSpec("pressure", "DESC")] + ... order_by=[OrderSpec("temperature", "ASC"), OrderSpec("pressure", "DESC")], ... ) Search for features with spatial filters: >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, - ... filter={"stWithin": { - ... "property": "location", - ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"} - ... }} + ... filter={ + ... "stWithin": { + ... "property": "location", + ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"}, + ... } + ... }, ... ) Combining multiple filters: >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, - ... filter={"and": [ - ... {"range": {"property": "temperature", "gt": 12.0}}, - ... {"stWithin": { - ... "property": "location", - ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"} - ... }} - ... ]} + ... filter={ + ... "and": [ + ... {"range": {"property": "temperature", "gt": 12.0}}, + ... { + ... "stWithin": { + ... "property": "location", + ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"}, + ... } + ... }, + ... ] + ... }, ... ) >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, - ... filter={"or": [ - ... {"range": {"property": "temperature", "gt": 12.0}}, - ... {"stWithin": { - ... "property": "location", - ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"} - ... }} - ... ]} + ... filter={ + ... "or": [ + ... {"range": {"property": "temperature", "gt": 12.0}}, + ... { + ... "stWithin": { + ... "property": "location", + ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"}, + ... } + ... }, + ... ] + ... }, ... ) """ resource_path = self._feature_resource_path(feature_type_external_id) + "/search" @@ -710,11 +715,11 @@ async def stream_features( >>> # async_client = AsyncCogniteClient() # another option >>> my_feature = client.geospatial.create_features( ... feature_type_external_id="my_feature_type", - ... feature=Feature(external_id="my_feature", temperature=12.4) + ... feature=Feature(external_id="my_feature", temperature=12.4), ... ) >>> features = client.geospatial.stream_features( ... feature_type_external_id="my_feature_type", - ... filter={"range": {"property": "temperature", "gt": 12.0}} + ... filter={"range": {"property": "temperature", "gt": 12.0}}, ... ) >>> for f in features: ... # do something with the features @@ -724,7 +729,7 @@ async def stream_features( >>> features = client.geospatial.stream_features( ... feature_type_external_id="my_feature_type", ... filter={}, - ... properties={"temperature": {}, "pressure": {}} + ... properties={"temperature": {}, "pressure": {}}, ... ) >>> for f in features: ... # do something with the features @@ -771,16 +776,17 @@ async def aggregate_features( >>> # async_client = AsyncCogniteClient() # another option >>> my_feature = client.geospatial.create_features( ... feature_type_external_id="my_feature_type", - ... feature=Feature(external_id="my_feature", temperature=12.4) + ... feature=Feature(external_id="my_feature", temperature=12.4), ... ) >>> res = client.geospatial.aggregate_features( ... feature_type_external_id="my_feature_type", ... filter={"range": {"property": "temperature", "gt": 12.0}}, ... group_by=["category"], ... order_by=[OrderSpec("category", "ASC")], - ... output={"min_temperature": {"min": {"property": "temperature"}}, - ... "max_volume": {"max": {"property": "volume"}} - ... } + ... output={ + ... "min_temperature": {"min": {"property": "temperature"}}, + ... "max_volume": {"max": {"property": "volume"}}, + ... }, ... ) >>> for a in res: ... # loop over aggregates in different groups @@ -881,37 +887,37 @@ async def create_coordinate_reference_systems( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> custom_crs = CoordinateReferenceSystemWrite( - ... srid = 121111, + ... srid=121111, ... wkt=( - ... 'PROJCS["NTF (Paris) / Lambert zone II",' - ... ' GEOGCS["NTF (Paris)",' - ... ' DATUM["Nouvelle_Triangulation_Francaise_Paris",' - ... ' SPHEROID["Clarke 1880 (IGN)",6378249.2,293.4660212936265,' - ... ' AUTHORITY["EPSG","7011"]],' - ... ' TOWGS84[-168,-60,320,0,0,0,0],' - ... ' AUTHORITY["EPSG","6807"]],' - ... ' PRIMEM["Paris",2.33722917,' - ... ' AUTHORITY["EPSG","8903"]],' - ... ' UNIT["grad",0.01570796326794897,' - ... ' AUTHORITY["EPSG","9105"]], ' - ... ' AUTHORITY["EPSG","4807"]],' - ... ' PROJECTION["Lambert_Conformal_Conic_1SP"],' - ... ' PARAMETER["latitude_of_origin",52],' - ... ' PARAMETER["central_meridian",0],' - ... ' PARAMETER["scale_factor",0.99987742],' - ... ' PARAMETER["false_easting",600000],' - ... ' PARAMETER["false_northing",2200000],' - ... ' UNIT["metre",1,' - ... ' AUTHORITY["EPSG","9001"]],' - ... ' AXIS["X",EAST],' - ... ' AXIS["Y",NORTH],' - ... ' AUTHORITY["EPSG","27572"]]' + ... 'PROJCS["NTF (Paris) / Lambert zone II",' + ... ' GEOGCS["NTF (Paris)",' + ... ' DATUM["Nouvelle_Triangulation_Francaise_Paris",' + ... ' SPHEROID["Clarke 1880 (IGN)",6378249.2,293.4660212936265,' + ... ' AUTHORITY["EPSG","7011"]],' + ... " TOWGS84[-168,-60,320,0,0,0,0]," + ... ' AUTHORITY["EPSG","6807"]],' + ... ' PRIMEM["Paris",2.33722917,' + ... ' AUTHORITY["EPSG","8903"]],' + ... ' UNIT["grad",0.01570796326794897,' + ... ' AUTHORITY["EPSG","9105"]], ' + ... ' AUTHORITY["EPSG","4807"]],' + ... ' PROJECTION["Lambert_Conformal_Conic_1SP"],' + ... ' PARAMETER["latitude_of_origin",52],' + ... ' PARAMETER["central_meridian",0],' + ... ' PARAMETER["scale_factor",0.99987742],' + ... ' PARAMETER["false_easting",600000],' + ... ' PARAMETER["false_northing",2200000],' + ... ' UNIT["metre",1,' + ... ' AUTHORITY["EPSG","9001"]],' + ... ' AXIS["X",EAST],' + ... ' AXIS["Y",NORTH],' + ... ' AUTHORITY["EPSG","27572"]]' ... ), ... proj_string=( - ... '+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 ' - ... '+x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 ' - ... '+towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs' - ... ) + ... "+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 " + ... "+x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 " + ... "+towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs" + ... ), ... ) >>> crs = client.geospatial.create_coordinate_reference_systems(custom_crs) """ @@ -994,8 +1000,14 @@ async def put_raster( >>> feature_type = ... >>> feature = ... >>> raster_property_name = ... - >>> metadata = client.geospatial.put_raster(feature_type.external_id, feature.external_id, - ... raster_property_name, "XYZ", 3857, file) + >>> metadata = client.geospatial.put_raster( + ... feature_type.external_id, + ... feature.external_id, + ... raster_property_name, + ... "XYZ", + ... 3857, + ... file, + ... ) """ query_params = f"format={raster_format}&srid={raster_srid}" if allow_crs_transformation: @@ -1041,7 +1053,9 @@ async def delete_raster( >>> feature_type = ... >>> feature = ... >>> raster_property_name = ... - >>> client.geospatial.delete_raster(feature_type.external_id, feature.external_id, raster_property_name) + >>> client.geospatial.delete_raster( + ... feature_type.external_id, feature.external_id, raster_property_name + ... ) """ await self._post( self._raster_resource_path(feature_type_external_id, feature_external_id, raster_property_name) + "/delete", @@ -1086,8 +1100,13 @@ async def get_raster( >>> feature_type = ... >>> feature = ... >>> raster_property_name = ... - >>> raster_data = client.geospatial.get_raster(feature_type.external_id, feature.external_id, - ... raster_property_name, "XYZ", {"SIGNIFICANT_DIGITS": "4"}) + >>> raster_data = client.geospatial.get_raster( + ... feature_type.external_id, + ... feature.external_id, + ... raster_property_name, + ... "XYZ", + ... {"SIGNIFICANT_DIGITS": "4"}, + ... ) """ url_path = self._raster_resource_path(feature_type_external_id, feature_external_id, raster_property_name) response = await self._post( @@ -1121,11 +1140,19 @@ async def compute( Compute the transformation of an ewkt geometry from one SRID to another: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.geospatial import GeospatialGeometryTransformComputeFunction, GeospatialGeometryValueComputeFunction + >>> from cognite.client.data_classes.geospatial import ( + ... GeospatialGeometryTransformComputeFunction, + ... GeospatialGeometryValueComputeFunction, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> compute_function = GeospatialGeometryTransformComputeFunction(GeospatialGeometryValueComputeFunction("SRID=4326;POLYGON((0 0,10 0,10 10,0 10,0 0))"), srid=23031) - >>> compute_result = client.geospatial.compute(output = {"output": compute_function}) + >>> compute_function = GeospatialGeometryTransformComputeFunction( + ... GeospatialGeometryValueComputeFunction( + ... "SRID=4326;POLYGON((0 0,10 0,10 10,0 10,0 0))" + ... ), + ... srid=23031, + ... ) + >>> compute_result = client.geospatial.compute(output={"output": compute_function}) """ res = await self._post( f"{GeospatialAPI._RESOURCE_PATH}/compute", diff --git a/cognite/client/_api/hosted_extractors/destinations.py b/cognite/client/_api/hosted_extractors/destinations.py index 5391ec0985..c5bf4f39c8 100644 --- a/cognite/client/_api/hosted_extractors/destinations.py +++ b/cognite/client/_api/hosted_extractors/destinations.py @@ -91,11 +91,13 @@ async def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.hosted_extractors.destinations.retrieve('myDestination') + >>> res = client.hosted_extractors.destinations.retrieve("myDestination") Get multiple destinations by id: - >>> res = client.hosted_extractors.destinations.retrieve(["myDestination", "myDestination2"], ignore_unknown_ids=True) + >>> res = client.hosted_extractors.destinations.retrieve( + ... ["myDestination", "myDestination2"], ignore_unknown_ids=True + ... ) """ self._warning.warn() @@ -161,10 +163,17 @@ async def create(self, items: DestinationWrite | Sequence[DestinationWrite]) -> Create new destination: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.hosted_extractors import DestinationWrite, SessionWrite + >>> from cognite.client.data_classes.hosted_extractors import ( + ... DestinationWrite, + ... SessionWrite, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> destination = DestinationWrite(external_id='my_dest', credentials=SessionWrite("my_nonce"), target_data_set_id=123) + >>> destination = DestinationWrite( + ... external_id="my_dest", + ... credentials=SessionWrite("my_nonce"), + ... target_data_set_id=123, + ... ) >>> res = client.hosted_extractors.destinations.create(destination) """ self._warning.warn() @@ -212,7 +221,7 @@ async def update( >>> from cognite.client.data_classes.hosted_extractors import DestinationUpdate >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> destination = DestinationUpdate('my_dest').target_data_set_id.set(123) + >>> destination = DestinationUpdate("my_dest").target_data_set_id.set(123) >>> res = client.hosted_extractors.destinations.update(destination) """ self._warning.warn() @@ -254,7 +263,7 @@ async def list( Iterate over chunks of destinations to reduce memory load: >>> for destination_list in client.hosted_extractors.destinations(chunk_size=25): - ... destination_list # do something with the destinationss + ... destination_list # do something with the destinationss """ self._warning.warn() return await self._list( diff --git a/cognite/client/_api/hosted_extractors/jobs.py b/cognite/client/_api/hosted_extractors/jobs.py index a21842d5e3..4d357b3d62 100644 --- a/cognite/client/_api/hosted_extractors/jobs.py +++ b/cognite/client/_api/hosted_extractors/jobs.py @@ -91,11 +91,13 @@ async def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.hosted_extractors.jobs.retrieve('myJob') + >>> res = client.hosted_extractors.jobs.retrieve("myJob") Get multiple jobs by id: - >>> res = client.hosted_extractors.jobs.retrieve(["myJob", "myOtherJob"], ignore_unknown_ids=True) + >>> res = client.hosted_extractors.jobs.retrieve( + ... ["myJob", "myOtherJob"], ignore_unknown_ids=True + ... ) """ self._warning.warn() @@ -162,7 +164,9 @@ async def create(self, items: JobWrite | Sequence[JobWrite]) -> Job | JobList: >>> from cognite.client.data_classes.hosted_extractors import EventHubSourceWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> job_write = EventHubSourceWrite('my_event_hub', 'http://myeventhub.com', "My EventHub", 'my_key', 'my_value') + >>> job_write = EventHubSourceWrite( + ... "my_event_hub", "http://myeventhub.com", "My EventHub", "my_key", "my_value" + ... ) >>> job = client.hosted_extractors.jobs.create(job_write) """ self._warning.warn() @@ -210,7 +214,7 @@ async def update( >>> from cognite.client.data_classes.hosted_extractors import EventHubSourceUpdate >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> job = EventHubSourceUpdate('my_event_hub').event_hub_name.set("My Updated EventHub") + >>> job = EventHubSourceUpdate("my_event_hub").event_hub_name.set("My Updated EventHub") >>> updated_job = client.hosted_extractors.jobs.update(job) """ self._warning.warn() @@ -252,7 +256,7 @@ async def list( Iterate over chunks of jobs to reduce memory load: >>> for job_list in client.hosted_extractors.jobs(chunk_size=25): - ... job_list # do something with the jobs + ... job_list # do something with the jobs """ self._warning.warn() return await self._list( diff --git a/cognite/client/_api/hosted_extractors/mappings.py b/cognite/client/_api/hosted_extractors/mappings.py index 1d513b0af5..73f8aa43d2 100644 --- a/cognite/client/_api/hosted_extractors/mappings.py +++ b/cognite/client/_api/hosted_extractors/mappings.py @@ -84,11 +84,13 @@ async def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.hosted_extractors.mappings.retrieve('myMapping') + >>> res = client.hosted_extractors.mappings.retrieve("myMapping") Get multiple mappings by id: - >>> res = client.hosted_extractors.mappings.retrieve(["myMapping", "myMapping2"], ignore_unknown_ids=True) + >>> res = client.hosted_extractors.mappings.retrieve( + ... ["myMapping", "myMapping2"], ignore_unknown_ids=True + ... ) """ self._warning.warn() @@ -156,7 +158,12 @@ async def create(self, items: MappingWrite | Sequence[MappingWrite]) -> Mapping >>> from cognite.client.data_classes.hosted_extractors import MappingWrite, CustomMapping >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> mapping = MappingWrite(external_id="my_mapping", mapping=CustomMapping("some expression"), published=True, input="json") + >>> mapping = MappingWrite( + ... external_id="my_mapping", + ... mapping=CustomMapping("some expression"), + ... published=True, + ... input="json", + ... ) >>> res = client.hosted_extractors.mappings.create(mapping) """ self._warning.warn() @@ -193,7 +200,7 @@ async def update( >>> from cognite.client.data_classes.hosted_extractors import MappingUpdate >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> mapping = MappingUpdate('my_mapping').published.set(False) + >>> mapping = MappingUpdate("my_mapping").published.set(False) >>> res = client.hosted_extractors.mappings.update(mapping) """ self._warning.warn() @@ -234,7 +241,7 @@ async def list( Iterate over chunks of mappings to reduce memory load: >>> for mapping_list in client.hosted_extractors.mappings(chunk_size=25): - ... mapping_list # do something with the mappings + ... mapping_list # do something with the mappings """ self._warning.warn() return await self._list( diff --git a/cognite/client/_api/hosted_extractors/sources.py b/cognite/client/_api/hosted_extractors/sources.py index 74fa149ed4..6aca9f2937 100644 --- a/cognite/client/_api/hosted_extractors/sources.py +++ b/cognite/client/_api/hosted_extractors/sources.py @@ -84,11 +84,13 @@ async def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.hosted_extractors.sources.retrieve('myMQTTSource') + >>> res = client.hosted_extractors.sources.retrieve("myMQTTSource") Get multiple sources by id: - >>> res = client.hosted_extractors.sources.retrieve(["myMQTTSource", "MyEventHubSource"], ignore_unknown_ids=True) + >>> res = client.hosted_extractors.sources.retrieve( + ... ["myMQTTSource", "MyEventHubSource"], ignore_unknown_ids=True + ... ) """ self._warning.warn() @@ -155,7 +157,9 @@ async def create(self, items: SourceWrite | Sequence[SourceWrite]) -> Source | S >>> from cognite.client.data_classes.hosted_extractors import EventHubSourceWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> source = EventHubSourceWrite('my_event_hub', 'http://myeventhub.com', "My EventHub", 'my_key', 'my_value') + >>> source = EventHubSourceWrite( + ... "my_event_hub", "http://myeventhub.com", "My EventHub", "my_key", "my_value" + ... ) >>> res = client.hosted_extractors.sources.create(source) """ self._warning.warn() @@ -203,7 +207,9 @@ async def update( >>> from cognite.client.data_classes.hosted_extractors import EventHubSourceUpdate >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> source = EventHubSourceUpdate('my_event_hub').event_hub_name.set("My Updated EventHub") + >>> source = EventHubSourceUpdate("my_event_hub").event_hub_name.set( + ... "My Updated EventHub" + ... ) >>> res = client.hosted_extractors.sources.update(source) """ self._warning.warn() @@ -258,7 +264,7 @@ async def list( Iterate over chunks of sources to reduce memory load: >>> for source_list in client.hosted_extractors.sources(chunk_size=25): - ... source_list # do something with the sources + ... source_list # do something with the sources """ self._warning.warn() return await self._list( diff --git a/cognite/client/_api/iam/__init__.py b/cognite/client/_api/iam/__init__.py index 067556b127..1815d87025 100644 --- a/cognite/client/_api/iam/__init__.py +++ b/cognite/client/_api/iam/__init__.py @@ -135,26 +135,28 @@ def compare_capabilities( >>> to_check = [ ... AssetsAcl( ... actions=[AssetsAcl.Action.Read, AssetsAcl.Action.Write], - ... scope=AssetsAcl.Scope.All()), + ... scope=AssetsAcl.Scope.All(), + ... ), ... EventsAcl( ... actions=[EventsAcl.Action.Write], ... scope=EventsAcl.Scope.DataSet([123]), - ... )] + ... ), + ... ] >>> missing = client.iam.compare_capabilities( - ... existing_capabilities=my_groups, - ... desired_capabilities=to_check) + ... existing_capabilities=my_groups, desired_capabilities=to_check + ... ) >>> if missing: ... pass # do something Capabilities can also be passed as dictionaries: >>> to_check = [ - ... {'assetsAcl': {'actions': ['READ', 'WRITE'], 'scope': {'all': {}}}}, - ... {'eventsAcl': {'actions': ['WRITE'], 'scope': {'datasetScope': {'ids': [123]}}}}, + ... {"assetsAcl": {"actions": ["READ", "WRITE"], "scope": {"all": {}}}}, + ... {"eventsAcl": {"actions": ["WRITE"], "scope": {"datasetScope": {"ids": [123]}}}}, ... ] >>> missing = client.iam.compare_capabilities( - ... existing_capabilities=my_groups, - ... desired_capabilities=to_check) + ... existing_capabilities=my_groups, desired_capabilities=to_check + ... ) You may also load capabilities from a dict-representation directly into ACLs (access-control list) by using ``Capability.load``. This will also ensure that the capabilities are valid. @@ -227,19 +229,21 @@ async def verify_capabilities(self, desired_capabilities: ComparableCapability) >>> to_check = [ ... AssetsAcl( ... actions=[AssetsAcl.Action.Read, AssetsAcl.Action.Write], - ... scope=AssetsAcl.Scope.All()), + ... scope=AssetsAcl.Scope.All(), + ... ), ... EventsAcl( ... actions=[EventsAcl.Action.Write], ... scope=EventsAcl.Scope.DataSet([123]), - ... )] + ... ), + ... ] >>> if missing := client.iam.verify_capabilities(to_check): ... pass # do something Capabilities can also be passed as dictionaries: >>> to_check = [ - ... {'assetsAcl': {'actions': ['READ', 'WRITE'], 'scope': {'all': {}}}}, - ... {'eventsAcl': {'actions': ['WRITE'], 'scope': {'datasetScope': {'ids': [123]}}}}, + ... {"assetsAcl": {"actions": ["READ", "WRITE"], "scope": {"all": {}}}}, + ... {"eventsAcl": {"actions": ["WRITE"], "scope": {"datasetScope": {"ids": [123]}}}}, ... ] >>> missing = client.iam.verify_capabilities(to_check) diff --git a/cognite/client/_api/iam/groups.py b/cognite/client/_api/iam/groups.py index 69d4993485..1a63cfe8de 100644 --- a/cognite/client/_api/iam/groups.py +++ b/cognite/client/_api/iam/groups.py @@ -97,7 +97,8 @@ async def create(self, group: Group | GroupWrite | Sequence[Group] | Sequence[Gr >>> # async_client = AsyncCogniteClient() # another option >>> my_capabilities = [ ... AssetsAcl([AssetsAcl.Action.Read], AssetsAcl.Scope.All()), - ... EventsAcl([EventsAcl.Action.Write], EventsAcl.Scope.DataSet([123, 456]))] + ... EventsAcl([EventsAcl.Action.Write], EventsAcl.Scope.DataSet([123, 456])), + ... ] >>> my_group = GroupWrite(name="My Group", capabilities=my_capabilities) >>> res = client.iam.groups.create(my_group) @@ -108,7 +109,8 @@ async def create(self, group: Group | GroupWrite | Sequence[Group] | Sequence[Gr >>> grp = GroupWrite( ... name="Externally managed group", ... capabilities=my_capabilities, - ... source_id="b7c9a5a4...") + ... source_id="b7c9a5a4...", + ... ) >>> res = client.iam.groups.create(grp) Create a group whose members are managed internally by Cognite. This group may grant access through @@ -125,7 +127,8 @@ async def create(self, group: Group | GroupWrite | Sequence[Group] | Sequence[Gr >>> user_list_group = GroupWrite( ... name="Specfic users only", ... capabilities=my_capabilities, - ... members=["XRsSD1k3mTIKG", "M0SxY6bM9Jl"]) + ... members=["XRsSD1k3mTIKG", "M0SxY6bM9Jl"], + ... ) >>> res = client.iam.groups.create([user_list_group, all_group]) Capabilities are often defined in configuration files, like YAML or JSON. You may convert capabilities @@ -134,8 +137,8 @@ async def create(self, group: Group | GroupWrite | Sequence[Group] | Sequence[Gr >>> from cognite.client.data_classes.capabilities import Capability >>> unparsed_capabilities = [ - ... {'assetsAcl': {'actions': ['READ', 'WRITE'], 'scope': {'all': {}}}}, - ... {'eventsAcl': {'actions': ['WRITE'], 'scope': {'datasetScope': {'ids': [123]}}}}, + ... {"assetsAcl": {"actions": ["READ", "WRITE"], "scope": {"all": {}}}}, + ... {"eventsAcl": {"actions": ["WRITE"], "scope": {"datasetScope": {"ids": [123]}}}}, ... ] >>> acls = [Capability.load(cap) for cap in unparsed_capabilities] >>> group = GroupWrite(name="Another group", capabilities=acls) diff --git a/cognite/client/_api/labels.py b/cognite/client/_api/labels.py index 56cf34c289..8f44a8c8d2 100644 --- a/cognite/client/_api/labels.py +++ b/cognite/client/_api/labels.py @@ -163,7 +163,7 @@ async def list( Iterate over chunks of label definitions to reduce memory load: >>> for label_list in client.labels(chunk_size=2500): - ... label_list # do something with the type definitions + ... label_list # do something with the type definitions """ data_set_ids_processed = process_data_set_ids(data_set_ids, data_set_external_ids) @@ -202,7 +202,12 @@ async def create( >>> from cognite.client.data_classes import LabelDefinitionWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> labels = [LabelDefinitionWrite(external_id="ROTATING_EQUIPMENT", name="Rotating equipment"), LabelDefinitionWrite(external_id="PUMP", name="pump")] + >>> labels = [ + ... LabelDefinitionWrite( + ... external_id="ROTATING_EQUIPMENT", name="Rotating equipment" + ... ), + ... LabelDefinitionWrite(external_id="PUMP", name="pump"), + ... ] >>> res = client.labels.create(labels) """ if isinstance(label, Sequence): diff --git a/cognite/client/_api/postgres_gateway/tables.py b/cognite/client/_api/postgres_gateway/tables.py index f2de65c6c0..efb03ce0bd 100644 --- a/cognite/client/_api/postgres_gateway/tables.py +++ b/cognite/client/_api/postgres_gateway/tables.py @@ -78,8 +78,11 @@ async def create(self, username: str, items: pg.TableWrite | Sequence[pg.TableWr >>> from cognite.client.data_classes.postgres_gateway import ViewTableWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> table = ViewTableWrite(tablename="myCustom", options=ViewId(space="mySpace", external_id="myExternalId", version="v1")) - >>> res = client.postgres_gateway.tables.create("myUserName",table) + >>> table = ViewTableWrite( + ... tablename="myCustom", + ... options=ViewId(space="mySpace", external_id="myExternalId", version="v1"), + ... ) + >>> res = client.postgres_gateway.tables.create("myUserName", table) """ return await self._create_multiple( @@ -123,11 +126,13 @@ async def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.postgres_gateway.tables.retrieve("myUserName", 'myCustom') + >>> res = client.postgres_gateway.tables.retrieve("myUserName", "myCustom") Get multiple custom tables by id: - >>> res = client.postgres_gateway.tables.retrieve("myUserName", ["myCustom", "myCustom2"]) + >>> res = client.postgres_gateway.tables.retrieve( + ... "myUserName", ["myCustom", "myCustom2"] + ... ) """ return await self._retrieve_multiple( @@ -202,7 +207,7 @@ async def list( Iterate over chunks of tables to reduce memory load: >>> for table_list in client.postgres_gateway.tables(chunk_size=25): - ... table_list # do something with the custom tables + ... table_list # do something with the custom tables """ return await self._list( diff --git a/cognite/client/_api/postgres_gateway/users.py b/cognite/client/_api/postgres_gateway/users.py index ac86bb2616..35ecc841ef 100644 --- a/cognite/client/_api/postgres_gateway/users.py +++ b/cognite/client/_api/postgres_gateway/users.py @@ -83,13 +83,16 @@ async def create(self, user: UserWrite | Sequence[UserWrite]) -> UserCreated | U >>> import os >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.postgres_gateway import UserWrite, SessionCredentials + >>> from cognite.client.data_classes.postgres_gateway import ( + ... UserWrite, + ... SessionCredentials, + ... ) >>> from cognite.client.data_classes import ClientCredentials >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> session = client.iam.sessions.create( ... ClientCredentials(os.environ["IDP_CLIENT_ID"], os.environ["IDP_CLIENT_SECRET"]), - ... session_type="CLIENT_CREDENTIALS" + ... session_type="CLIENT_CREDENTIALS", ... ) >>> user = UserWrite(credentials=SessionCredentials(nonce=session.nonce)) >>> res = client.postgres_gateway.users.create(user) @@ -125,15 +128,20 @@ async def update(self, items: UserUpdate | UserWrite | Sequence[UserUpdate | Use >>> import os >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.postgres_gateway import UserUpdate, SessionCredentials + >>> from cognite.client.data_classes.postgres_gateway import ( + ... UserUpdate, + ... SessionCredentials, + ... ) >>> from cognite.client.data_classes import ClientCredentials >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> session = client.iam.sessions.create( ... ClientCredentials(os.environ["IDP_CLIENT_ID"], os.environ["IDP_CLIENT_SECRET"]), - ... session_type="CLIENT_CREDENTIALS" + ... session_type="CLIENT_CREDENTIALS", + ... ) + >>> update = UserUpdate("myUser").credentials.set( + ... SessionCredentials(nonce=session.nonce) ... ) - >>> update = UserUpdate('myUser').credentials.set(SessionCredentials(nonce=session.nonce)) >>> res = client.postgres_gateway.users.update(update) """ @@ -237,7 +245,7 @@ async def list(self, limit: int = DEFAULT_LIMIT_READ) -> UserList: Iterate over chunks of users to reduce memory load: >>> for user_list in client.postgres_gateway.users(chunk_size=25): - ... user_list # do something with the users + ... user_list # do something with the users """ return await self._list( diff --git a/cognite/client/_api/raw/databases.py b/cognite/client/_api/raw/databases.py index cc5e9c92bd..febb62636b 100644 --- a/cognite/client/_api/raw/databases.py +++ b/cognite/client/_api/raw/databases.py @@ -139,6 +139,6 @@ async def list(self, limit: int | None = DEFAULT_LIMIT_READ) -> DatabaseList: Iterate over chunks of databases to reduce memory load: >>> for db_list in client.raw.databases(chunk_size=2500): - ... db_list # do something with the dbs + ... db_list # do something with the dbs """ return await self._list(list_cls=DatabaseList, resource_cls=Database, method="GET", limit=limit) diff --git a/cognite/client/_api/raw/rows.py b/cognite/client/_api/raw/rows.py index 794926edaa..95b31462b7 100644 --- a/cognite/client/_api/raw/rows.py +++ b/cognite/client/_api/raw/rows.py @@ -271,8 +271,10 @@ async def insert( >>> from cognite.client.data_classes import RowWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> rows = [RowWrite(key="r1", columns={"col1": "val1", "col2": "val1"}), - ... RowWrite(key="r2", columns={"col1": "val2", "col2": "val2"})] + >>> rows = [ + ... RowWrite(key="r1", columns={"col1": "val1", "col2": "val1"}), + ... RowWrite(key="r2", columns={"col1": "val2", "col2": "val2"}), + ... ] >>> client.raw.rows.insert("db1", "table1", rows) You may also insert a dictionary directly: @@ -328,10 +330,9 @@ async def insert_dataframe( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> df = pd.DataFrame( - ... {"col-a": [1, 3, None], "col-b": [2, -1, 9]}, - ... index=["r1", "r2", "r3"]) - >>> res = client.raw.rows.insert_dataframe( - ... "db1", "table1", df, dropna=True) + ... {"col-a": [1, 3, None], "col-b": [2, -1, 9]}, index=["r1", "r2", "r3"] + ... ) + >>> res = client.raw.rows.insert_dataframe("db1", "table1", df, dropna=True) """ if not dataframe.index.is_unique: raise ValueError("Dataframe index is not unique (used for the row keys)") @@ -578,7 +579,7 @@ async def list( Iterate through all rows one-by-one to reduce memory load (no concurrency used): - >>> for row in client.raw.rows("db1", "t1", columns=["col1","col2"]): + >>> for row in client.raw.rows("db1", "t1", columns=["col1", "col2"]): ... val1 = row["col1"] # You may access the data directly ... val2 = row.get("col2") # ...or use '.get' when keys can be missing diff --git a/cognite/client/_api/raw/tables.py b/cognite/client/_api/raw/tables.py index 69228975c1..74a3e6a8f8 100644 --- a/cognite/client/_api/raw/tables.py +++ b/cognite/client/_api/raw/tables.py @@ -177,7 +177,7 @@ async def list(self, db_name: str, limit: int | None = DEFAULT_LIMIT_READ) -> ra Iterate over chunks of tables to reduce memory load: >>> for table_list in client.raw.tables(db_name="db1", chunk_size=25): - ... table_list # do something with the tables + ... table_list # do something with the tables """ tb = await self._list( list_cls=raw.TableList, diff --git a/cognite/client/_api/relationships.py b/cognite/client/_api/relationships.py index 32d7d9308d..d867f5a41e 100644 --- a/cognite/client/_api/relationships.py +++ b/cognite/client/_api/relationships.py @@ -373,7 +373,7 @@ async def create( ... target_external_id="target_ext_id", ... target_type="event", ... confidence=0.1, - ... data_set_id=1234 + ... data_set_id=1234, ... ) >>> flowrel2 = RelationshipWrite( ... external_id="flow_2", @@ -382,9 +382,9 @@ async def create( ... target_external_id="target_ext_id", ... target_type="event", ... confidence=0.1, - ... data_set_id=1234 + ... data_set_id=1234, ... ) - >>> res = client.relationships.create([flowrel1,flowrel2]) + >>> res = client.relationships.create([flowrel1, flowrel2]) """ assert_type(relationship, "relationship", [RelationshipCore, Sequence]) if isinstance(relationship, Sequence): @@ -438,7 +438,11 @@ async def update( Perform a partial update on a relationship, setting a source_external_id and a confidence: >>> from cognite.client.data_classes import RelationshipUpdate - >>> my_update = RelationshipUpdate(external_id="flow_1").source_external_id.set("alternate_source").confidence.set(0.97) + >>> my_update = ( + ... RelationshipUpdate(external_id="flow_1") + ... .source_external_id.set("alternate_source") + ... .confidence.set(0.97) + ... ) >>> res1 = client.relationships.update(my_update) >>> # Remove an already set optional field like so >>> another_update = RelationshipUpdate(external_id="flow_1").confidence.set(None) @@ -503,9 +507,11 @@ async def upsert( ... source_external_id="new_source", ... source_type="asset", ... target_external_id="new_target", - ... target_type="event" + ... target_type="event", + ... ) + >>> res = client.relationships.upsert( + ... [existing_relationship, new_relationship], mode="replace" ... ) - >>> res = client.relationships.upsert([existing_relationship, new_relationship], mode="replace") """ return await self._upsert_multiple( item, @@ -529,7 +535,7 @@ async def delete(self, external_id: str | SequenceNotStr[str], ignore_unknown_id >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.relationships.delete(external_id=["a","b"]) + >>> client.relationships.delete(external_id=["a", "b"]) """ await self._delete_multiple( identifiers=IdentifierSequence.load(external_ids=external_id), diff --git a/cognite/client/_api/sequence_data.py b/cognite/client/_api/sequence_data.py index 297a5a471d..d69236aa82 100644 --- a/cognite/client/_api/sequence_data.py +++ b/cognite/client/_api/sequence_data.py @@ -61,27 +61,32 @@ async def insert( ... SequenceWrite( ... columns=[ ... SequenceColumnWrite(value_type="STRING", external_id="col_a"), - ... SequenceColumnWrite(value_type="DOUBLE", external_id ="col_b") + ... SequenceColumnWrite(value_type="DOUBLE", external_id="col_b"), ... ], ... ) ... ) - >>> data = [(1, ['pi',3.14]), (2, ['e',2.72]) ] - >>> client.sequences.data.insert(columns=["col_a","col_b"], rows=data, id=1) + >>> data = [(1, ["pi", 3.14]), (2, ["e", 2.72])] + >>> client.sequences.data.insert(columns=["col_a", "col_b"], rows=data, id=1) They can also be provided as a list of API-style objects with a rowNumber and values field: - >>> data = [{"rowNumber": 123, "values": ['str',3]}, {"rowNumber": 456, "values": ["bar",42]} ] - >>> client.sequences.data.insert(data, id=1, columns=["col_a","col_b"]) # implicit columns are retrieved from metadata + >>> data = [ + ... {"rowNumber": 123, "values": ["str", 3]}, + ... {"rowNumber": 456, "values": ["bar", 42]}, + ... ] + >>> client.sequences.data.insert( + ... data, id=1, columns=["col_a", "col_b"] + ... ) # implicit columns are retrieved from metadata Or they can be a given as a dictionary with row number as the key, and the value is the data to be inserted at that row: - >>> data = {123 : ['str',3], 456 : ['bar',42] } - >>> client.sequences.data.insert(columns=['stringColumn','intColumn'], rows=data, id=1) + >>> data = {123: ["str", 3], 456: ["bar", 42]} + >>> client.sequences.data.insert(columns=["stringColumn", "intColumn"], rows=data, id=1) Finally, they can be a SequenceData object retrieved from another request. In this case columns from this object are used as well. - >>> data = client.sequences.data.retrieve(id=2,start=0,end=10) - >>> client.sequences.data.insert(rows=data, id=1,columns=None) + >>> data = client.sequences.data.retrieve(id=2, start=0, end=10) + >>> client.sequences.data.insert(rows=data, id=1, columns=None) """ match rows: case SequenceRows(): @@ -139,7 +144,7 @@ async def insert_dataframe( >>> import pandas as pd >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> df = pd.DataFrame({'col_a': [1, 2, 3], 'col_b': [4, 5, 6]}, index=[1, 2, 3]) + >>> df = pd.DataFrame({"col_a": [1, 2, 3], "col_b": [4, 5, 6]}, index=[1, 2, 3]) >>> client.sequences.data.insert_dataframe(df, id=123) """ if dropna: @@ -168,7 +173,7 @@ async def delete(self, rows: typing.Sequence[int], id: int | None = None, extern >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.sequences.data.delete(id=1, rows=[1,2,42]) + >>> client.sequences.data.delete(id=1, rows=[1, 2, 42]) """ post_obj = Identifier.of_either(id, external_id).as_dict() post_obj["rows"] = rows @@ -302,10 +307,14 @@ async def retrieve( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> res = client.sequences.data.retrieve(id=1) - >>> tuples = [(r,v) for r,v in res.items()] # You can use this iterator in for loops and list comprehensions, - >>> single_value = res[23] # ... get the values at a single row number, - >>> col = res.get_column(external_id='columnExtId') # ... get the array of values for a specific column, - >>> df = res.to_pandas() # ... or convert the result to a dataframe + >>> tuples = [ + ... (r, v) for r, v in res.items() + ... ] # You can use this iterator in for loops and list comprehensions, + >>> single_value = res[23] # ... get the values at a single row number, + >>> col = res.get_column( + ... external_id="columnExtId" + ... ) # ... get the array of values for a specific column, + >>> df = res.to_pandas() # ... or convert the result to a dataframe """ ident_sequence = IdentifierSequence.load(id, external_id) diff --git a/cognite/client/_api/sequences.py b/cognite/client/_api/sequences.py index 501e9c7574..bd62cef6c2 100644 --- a/cognite/client/_api/sequences.py +++ b/cognite/client/_api/sequences.py @@ -300,7 +300,9 @@ async def aggregate_cardinality_values( >>> from cognite.client.data_classes.sequences import SequenceProperty >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> count = client.sequences.aggregate_cardinality_values(SequenceProperty.metadata_key("efficiency")) + >>> count = client.sequences.aggregate_cardinality_values( + ... SequenceProperty.metadata_key("efficiency") + ... ) Count the number of timezones (metadata key) for sequences with the word "critical" in the description in your CDF project, but exclude timezones from america: @@ -312,7 +314,8 @@ async def aggregate_cardinality_values( >>> timezone_count = client.sequences.aggregate_cardinality_values( ... SequenceProperty.metadata_key("timezone"), ... advanced_filter=is_critical, - ... aggregate_filter=not_america) + ... aggregate_filter=not_america, + ... ) """ self._validate_filter(advanced_filter) return await self._advanced_aggregate( @@ -388,7 +391,9 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes.sequences import SequenceProperty >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> result = client.sequences.aggregate_unique_values(SequenceProperty.metadata_key("timezone")) + >>> result = client.sequences.aggregate_unique_values( + ... SequenceProperty.metadata_key("timezone") + ... ) >>> print(result.unique) Get the different metadata keys with count used for sequences created after 2020-01-01 in your CDF project: @@ -397,8 +402,12 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes.sequences import SequenceProperty >>> from cognite.client.utils import timestamp_to_ms >>> from datetime import datetime - >>> created_after_2020 = filters.Range(SequenceProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.sequences.aggregate_unique_values(SequenceProperty.metadata, advanced_filter=created_after_2020) + >>> created_after_2020 = filters.Range( + ... SequenceProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.sequences.aggregate_unique_values( + ... SequenceProperty.metadata, advanced_filter=created_after_2020 + ... ) >>> print(result.unique) Get the different metadata keys with count for sequences updated after 2020-01-01 in your CDF project, but exclude all metadata keys that @@ -407,8 +416,14 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes.sequences import SequenceProperty >>> from cognite.client.data_classes import aggregations as aggs, filters >>> not_test = aggs.Not(aggs.Prefix("test")) - >>> created_after_2020 = filters.Range(SequenceProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.sequences.aggregate_unique_values(SequenceProperty.metadata, advanced_filter=created_after_2020, aggregate_filter=not_test) + >>> created_after_2020 = filters.Range( + ... SequenceProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.sequences.aggregate_unique_values( + ... SequenceProperty.metadata, + ... advanced_filter=created_after_2020, + ... aggregate_filter=not_test, + ... ) >>> print(result.unique) """ self._validate_filter(advanced_filter) @@ -494,14 +509,20 @@ async def create( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> column_def = [ - ... SequenceColumnWrite(value_type="STRING", external_id="user", description="some description"), - ... SequenceColumnWrite(value_type="DOUBLE", external_id="amount") + ... SequenceColumnWrite( + ... value_type="STRING", external_id="user", description="some description" + ... ), + ... SequenceColumnWrite(value_type="DOUBLE", external_id="amount"), ... ] - >>> seq = client.sequences.create(SequenceWrite(external_id="my_sequence", columns=column_def)) + >>> seq = client.sequences.create( + ... SequenceWrite(external_id="my_sequence", columns=column_def) + ... ) Create a new sequence with the same column specifications as an existing sequence: - >>> seq2 = client.sequences.create(SequenceWrite(external_id="my_copied_sequence", columns=column_def)) + >>> seq2 = client.sequences.create( + ... SequenceWrite(external_id="my_copied_sequence", columns=column_def) + ... ) """ assert_type(sequence, "sequences", [typing.Sequence, Sequence, SequenceWrite]) @@ -530,7 +551,7 @@ async def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.sequences.delete(id=[1,2,3], external_id="3") + >>> client.sequences.delete(id=[1, 2, 3], external_id="3") """ await self._delete_multiple( identifiers=IdentifierSequence.load(ids=id, external_ids=external_id), @@ -580,7 +601,11 @@ async def update( Perform a partial update on a sequence, updating the description and adding a new field to metadata: >>> from cognite.client.data_classes import SequenceUpdate - >>> my_update = SequenceUpdate(id=1).description.set("New description").metadata.add({"key": "value"}) + >>> my_update = ( + ... SequenceUpdate(id=1) + ... .description.set("New description") + ... .metadata.add({"key": "value"}) + ... ) >>> res = client.sequences.update(my_update) **Updating column definitions** @@ -592,7 +617,9 @@ async def update( >>> from cognite.client.data_classes import SequenceUpdate, SequenceColumnWrite >>> >>> my_update = SequenceUpdate(id=1).columns.add( - ... SequenceColumnWrite(value_type ="STRING",external_id="user", description ="some description") + ... SequenceColumnWrite( + ... value_type="STRING", external_id="user", description="some description" + ... ) ... ) >>> res = client.sequences.update(my_update) @@ -601,8 +628,10 @@ async def update( >>> from cognite.client.data_classes import SequenceUpdate, SequenceColumnWrite >>> >>> column_def = [ - ... SequenceColumnWrite(value_type ="STRING",external_id="user", description ="some description"), - ... SequenceColumnWrite(value_type="DOUBLE", external_id="amount") + ... SequenceColumnWrite( + ... value_type="STRING", external_id="user", description="some description" + ... ), + ... SequenceColumnWrite(value_type="DOUBLE", external_id="amount"), ... ] >>> my_update = SequenceUpdate(id=1).columns.add(column_def) >>> res = client.sequences.update(my_update) @@ -618,7 +647,9 @@ async def update( >>> from cognite.client.data_classes import SequenceUpdate >>> - >>> my_update = SequenceUpdate(id=1).columns.remove(["col_external_id1","col_external_id2"]) + >>> my_update = SequenceUpdate(id=1).columns.remove( + ... ["col_external_id1", "col_external_id2"] + ... ) >>> res = client.sequences.update(my_update) Update existing columns: @@ -626,8 +657,12 @@ async def update( >>> from cognite.client.data_classes import SequenceUpdate, SequenceColumnUpdate >>> >>> column_updates = [ - ... SequenceColumnUpdate(external_id="col_external_id_1").external_id.set("new_col_external_id"), - ... SequenceColumnUpdate(external_id="col_external_id_2").description.set("my new description"), + ... SequenceColumnUpdate(external_id="col_external_id_1").external_id.set( + ... "new_col_external_id" + ... ), + ... SequenceColumnUpdate(external_id="col_external_id_2").description.set( + ... "my new description" + ... ), ... ] >>> my_update = SequenceUpdate(id=1).columns.modify(column_updates) >>> res = client.sequences.update(my_update) @@ -681,7 +716,7 @@ async def upsert( >>> new_sequence = SequenceWrite( ... external_id="new_sequence", ... description="New sequence", - ... columns=[SequenceColumnWrite(external_id="col1", value_type="STRING")] + ... columns=[SequenceColumnWrite(external_id="col1", value_type="STRING")], ... ) >>> res = client.sequences.upsert([existing_sequence, new_sequence], mode="replace") """ @@ -885,7 +920,7 @@ async def list( Iterate over chunks of sequences to reduce memory load: >>> for seq_list in client.sequences(chunk_size=2500): - ... seq_list # do something with the sequences + ... seq_list # do something with the sequences Using advanced filter, find all sequences that have a metadata key 'timezone' starting with 'Europe', and sort by external id ascending: @@ -901,20 +936,25 @@ async def list( for filtering and sorting, you can also use the `SequenceProperty` and `SortableSequenceProperty` Enums. >>> from cognite.client.data_classes import filters - >>> from cognite.client.data_classes.sequences import SequenceProperty, SortableSequenceProperty + >>> from cognite.client.data_classes.sequences import ( + ... SequenceProperty, + ... SortableSequenceProperty, + ... ) >>> in_timezone = filters.Prefix(SequenceProperty.metadata_key("timezone"), "Europe") >>> res = client.sequences.list( - ... advanced_filter=in_timezone, - ... sort=(SortableSequenceProperty.external_id, "asc")) + ... advanced_filter=in_timezone, sort=(SortableSequenceProperty.external_id, "asc") + ... ) Combine filter and advanced filter: >>> from cognite.client.data_classes import filters >>> not_instrument_lvl5 = filters.And( - ... filters.ContainsAny("labels", ["Level5"]), - ... filters.Not(filters.ContainsAny("labels", ["Instrument"])) + ... filters.ContainsAny("labels", ["Level5"]), + ... filters.Not(filters.ContainsAny("labels", ["Instrument"])), + ... ) + >>> res = client.sequences.list( + ... asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5 ... ) - >>> res = client.sequences.list(asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5) """ asset_subtree_ids_processed = process_asset_subtree_ids(asset_subtree_ids, asset_subtree_external_ids) diff --git a/cognite/client/_api/simulators/integrations.py b/cognite/client/_api/simulators/integrations.py index bfb3e03fb7..69798fc673 100644 --- a/cognite/client/_api/simulators/integrations.py +++ b/cognite/client/_api/simulators/integrations.py @@ -136,7 +136,7 @@ async def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.simulators.integrations.delete(ids=[1,2,3], external_ids="foo") + >>> client.simulators.integrations.delete(ids=[1, 2, 3], external_ids="foo") """ await self._delete_multiple( identifiers=IdentifierSequence.load(ids=ids, external_ids=external_ids), diff --git a/cognite/client/_api/simulators/models.py b/cognite/client/_api/simulators/models.py index 7e2f6dcb0b..e9c1e35f85 100644 --- a/cognite/client/_api/simulators/models.py +++ b/cognite/client/_api/simulators/models.py @@ -68,10 +68,7 @@ async def list( >>> from cognite.client.data_classes.simulators.filters import PropertySort >>> res = client.simulators.models.list( ... simulator_external_ids=["simulator_external_id"], - ... sort=PropertySort( - ... property="createdTime", - ... order="asc" - ... ) + ... sort=PropertySort(property="createdTime", order="asc"), ... ) """ @@ -126,7 +123,7 @@ async def retrieve( >>> res = client.simulators.models.retrieve(external_ids="model_external_id") Get multiple simulator models by ids: - >>> res = client.simulators.models.retrieve(ids=[1,2]) + >>> res = client.simulators.models.retrieve(ids=[1, 2]) Get multiple simulator models by external ids: >>> res = client.simulators.models.retrieve( @@ -216,13 +213,19 @@ async def create( >>> # async_client = AsyncCogniteClient() # another option >>> models = [ ... SimulatorModelWrite( - ... name="model1", simulator_external_id="sim1", type="SteadyState", - ... data_set_id=1, external_id="model_external_id" + ... name="model1", + ... simulator_external_id="sim1", + ... type="SteadyState", + ... data_set_id=1, + ... external_id="model_external_id", ... ), ... SimulatorModelWrite( - ... name="model2", simulator_external_id="sim2", type="SteadyState", - ... data_set_id=2, external_id="model_external_id2" - ... ) + ... name="model2", + ... simulator_external_id="sim2", + ... type="SteadyState", + ... data_set_id=2, + ... external_id="model_external_id2", + ... ), ... ] >>> res = client.simulators.models.create(models) """ @@ -252,7 +255,7 @@ async def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.simulators.models.delete(ids=[1,2,3], external_ids="model_external_id") + >>> client.simulators.models.delete(ids=[1, 2, 3], external_ids="model_external_id") """ await self._delete_multiple( identifiers=IdentifierSequence.load(ids=ids, external_ids=external_ids), diff --git a/cognite/client/_api/simulators/models_revisions.py b/cognite/client/_api/simulators/models_revisions.py index b6743ec314..2e98a20155 100644 --- a/cognite/client/_api/simulators/models_revisions.py +++ b/cognite/client/_api/simulators/models_revisions.py @@ -76,7 +76,7 @@ async def list( ... created_time=TimestampRange(min=0, max=1000000), ... last_updated_time=TimestampRange(min=0, max=1000000), ... sort=PropertySort(order="asc", property="createdTime"), - ... limit=10 + ... limit=10, ... ) """ model_revisions_filter = SimulatorModelRevisionsFilter( @@ -137,7 +137,7 @@ async def retrieve( ... ) Get multiple simulator model revisions by ids: - >>> res = client.simulators.models.revisions.retrieve(ids=[1,2]) + >>> res = client.simulators.models.revisions.retrieve(ids=[1, 2]) Get multiple simulator model revisions by external ids: >>> res = client.simulators.models.revisions.retrieve( @@ -239,7 +239,11 @@ async def create( Examples: Create new simulator model revisions: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.simulators import SimulatorModelRevisionWrite, SimulatorModelDependencyFileId, SimulatorModelRevisionDependency + >>> from cognite.client.data_classes.simulators import ( + ... SimulatorModelRevisionWrite, + ... SimulatorModelDependencyFileId, + ... SimulatorModelRevisionDependency, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> revisions = [ @@ -252,7 +256,7 @@ async def create( ... external_id="revision2", ... file_id=2, ... model_external_id="a_2", - ... external_dependencies = [ + ... external_dependencies=[ ... SimulatorModelRevisionDependency( ... file=SimulatorModelDependencyFileId(id=123), ... arguments={ @@ -260,7 +264,7 @@ async def create( ... "fieldB": "value2", ... }, ... ) - ... ] + ... ], ... ), ... ] >>> res = client.simulators.models.revisions.create(revisions) diff --git a/cognite/client/_api/simulators/routine_revisions.py b/cognite/client/_api/simulators/routine_revisions.py index dcc7210551..f83451404f 100644 --- a/cognite/client/_api/simulators/routine_revisions.py +++ b/cognite/client/_api/simulators/routine_revisions.py @@ -351,13 +351,11 @@ async def list( ... routine_external_ids=["routine_1"], ... all_versions=True, ... sort=PropertySort(order="asc", property="createdTime"), - ... include_all_fields=True + ... include_all_fields=True, ... ) List simulator routine revisions by kind: - >>> res = client.simulators.routines.revisions.list( - ... kind="long" - ... ) + >>> res = client.simulators.routines.revisions.list(kind="long") """ self._warning.warn() diff --git a/cognite/client/_api/simulators/routines.py b/cognite/client/_api/simulators/routines.py index 72a9353d0b..2d59fb80e6 100644 --- a/cognite/client/_api/simulators/routines.py +++ b/cognite/client/_api/simulators/routines.py @@ -133,7 +133,7 @@ async def create( ... simulator_integration_external_id="integration_ext_id_2", ... model_external_id="model_ext_id_2", ... kind="long", - ... ) + ... ), ... ] >>> res = client.simulators.routines.create(routines) """ @@ -164,7 +164,7 @@ async def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.simulators.routines.delete(ids=[1,2,3], external_ids="foo") + >>> client.simulators.routines.delete(ids=[1, 2, 3], external_ids="foo") """ self._warning.warn() await self._delete_multiple( @@ -209,16 +209,11 @@ async def list( >>> from cognite.client.data_classes.simulators.filters import PropertySort >>> res = client.simulators.routines.list( ... simulator_integration_external_ids=["integration_ext_id"], - ... sort=PropertySort( - ... property="createdTime", - ... order="desc" - ... ) + ... sort=PropertySort(property="createdTime", order="desc"), ... ) Filter on routine kind: - >>> res = client.simulators.routines.list( - ... kind="long" - ... ) + >>> res = client.simulators.routines.list(kind="long") """ self._warning.warn() @@ -307,8 +302,7 @@ async def run( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> run = client.simulators.routines.run( - ... routine_external_id="routine1", - ... log_severity="Debug" + ... routine_external_id="routine1", log_severity="Debug" ... ) Create new simulation run using routine and model revision external IDs: diff --git a/cognite/client/_api/simulators/runs.py b/cognite/client/_api/simulators/runs.py index b1d9d03d29..7ee073571e 100644 --- a/cognite/client/_api/simulators/runs.py +++ b/cognite/client/_api/simulators/runs.py @@ -189,8 +189,7 @@ async def list( Filter runs by status and simulator external ids: >>> res = client.simulators.runs.list( - ... simulator_external_ids=["PROSPER", "DWSIM"], - ... status="success" + ... simulator_external_ids=["PROSPER", "DWSIM"], status="success" ... ) Filter runs by time ranges: diff --git a/cognite/client/_api/synthetic_time_series.py b/cognite/client/_api/synthetic_time_series.py index 8749ca89fe..02043343e5 100644 --- a/cognite/client/_api/synthetic_time_series.py +++ b/cognite/client/_api/synthetic_time_series.py @@ -135,9 +135,8 @@ async def query( ... + ts{space:'my-space',externalId:'my-ts-xid'} ... ''' >>> dps = client.time_series.data.synthetic.query( - ... expressions=expression, - ... start="2w-ago", - ... end="now") + ... expressions=expression, start="2w-ago", end="now" + ... ) You can also specify variables for an easier query syntax: @@ -149,14 +148,15 @@ async def query( ... "C": NodeId("my-space", "my-ts-xid"), ... } >>> dps = client.time_series.data.synthetic.query( - ... expressions="A+B+C", start="2w-ago", end="2w-ahead", variables=variables) + ... expressions="A+B+C", start="2w-ago", end="2w-ahead", variables=variables + ... ) Use sympy to build complex expressions: >>> from sympy import symbols, cos, sin >>> x, y = symbols("x y") >>> dps = client.time_series.data.synthetic.query( - ... [sin(x), y*cos(x)], + ... [sin(x), y * cos(x)], ... start="2w-ago", ... end="now", ... variables={x: "foo", y: "bar"}, diff --git a/cognite/client/_api/three_d/asset_mapping.py b/cognite/client/_api/three_d/asset_mapping.py index 49eeea904c..baf3de3942 100644 --- a/cognite/client/_api/three_d/asset_mapping.py +++ b/cognite/client/_api/three_d/asset_mapping.py @@ -57,7 +57,8 @@ async def list( >>> from cognite.client.data_classes import BoundingBox3D >>> bbox = BoundingBox3D(min=[0.0, 0.0, 0.0], max=[1.0, 1.0, 1.0]) >>> res = client.three_d.asset_mappings.list( - ... model_id=1, revision_id=1, intersects_bounding_box=bbox) + ... model_id=1, revision_id=1, intersects_bounding_box=bbox + ... ) """ path = interpolate_and_url_encode(self._RESOURCE_PATH, model_id, revision_id) flt: dict[str, str | int | None] = {"nodeId": node_id, "assetId": asset_id} @@ -113,7 +114,9 @@ async def create( >>> my_mapping = ThreeDAssetMappingWrite(node_id=1, asset_id=1) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.three_d.asset_mappings.create(model_id=1, revision_id=1, asset_mapping=my_mapping) + >>> res = client.three_d.asset_mappings.create( + ... model_id=1, revision_id=1, asset_mapping=my_mapping + ... ) """ path = interpolate_and_url_encode(self._RESOURCE_PATH, model_id, revision_id) return await self._create_multiple( @@ -142,7 +145,9 @@ async def delete( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> mapping_to_delete = client.three_d.asset_mappings.list(model_id=1, revision_id=1)[0] - >>> res = client.three_d.asset_mappings.delete(model_id=1, revision_id=1, asset_mapping=mapping_to_delete) + >>> res = client.three_d.asset_mappings.delete( + ... model_id=1, revision_id=1, asset_mapping=mapping_to_delete + ... ) """ path = interpolate_and_url_encode(self._RESOURCE_PATH, model_id, revision_id) assert_type(asset_mapping, "asset_mapping", [Sequence, ThreeDAssetMapping]) diff --git a/cognite/client/_api/three_d/models.py b/cognite/client/_api/three_d/models.py index 592a1c2f3c..f30021962e 100644 --- a/cognite/client/_api/three_d/models.py +++ b/cognite/client/_api/three_d/models.py @@ -101,7 +101,7 @@ async def list(self, published: bool | None = None, limit: int | None = DEFAULT_ Iterate over chunks of 3d models to reduce memory load: >>> for model in client.three_d.models(chunk_size=50): - ... model # do something with the 3d model + ... model # do something with the 3d model """ return await self._list( list_cls=ThreeDModelList, @@ -152,7 +152,9 @@ async def create( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.three_d.models.create(name="My Model", data_set_id=1, metadata={"key1": "value1", "key2": "value2"}) + >>> res = client.three_d.models.create( + ... name="My Model", data_set_id=1, metadata={"key1": "value1", "key2": "value2"} + ... ) Create multiple new 3D Models: @@ -160,8 +162,14 @@ async def create( >>> from cognite.client.data_classes import ThreeDModelWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> my_model = ThreeDModelWrite(name="My Model", data_set_id=1, metadata={"key1": "value1", "key2": "value2"}) - >>> my_other_model = ThreeDModelWrite(name="My Other Model", data_set_id=1, metadata={"key1": "value1", "key2": "value2"}) + >>> my_model = ThreeDModelWrite( + ... name="My Model", data_set_id=1, metadata={"key1": "value1", "key2": "value2"} + ... ) + >>> my_other_model = ThreeDModelWrite( + ... name="My Other Model", + ... data_set_id=1, + ... metadata={"key1": "value1", "key2": "value2"}, + ... ) >>> res = client.three_d.models.create([my_model, my_other_model]) """ diff --git a/cognite/client/_api/three_d/revisions.py b/cognite/client/_api/three_d/revisions.py index 470d9bfbdd..47d31b76cd 100644 --- a/cognite/client/_api/three_d/revisions.py +++ b/cognite/client/_api/three_d/revisions.py @@ -189,7 +189,11 @@ async def update( Perform a partial update on a revision, updating the published property and adding a new field to metadata: >>> from cognite.client.data_classes import ThreeDModelRevisionUpdate - >>> my_update = ThreeDModelRevisionUpdate(id=1).published.set(False).metadata.add({"key": "value"}) + >>> my_update = ( + ... ThreeDModelRevisionUpdate(id=1) + ... .published.set(False) + ... .metadata.add({"key": "value"}) + ... ) >>> res = client.three_d.revisions.update(model_id=1, item=my_update) """ return await self._update_multiple( @@ -318,7 +322,17 @@ async def filter_nodes( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.three_d.revisions.filter_nodes(model_id=1, revision_id=1, properties={ "PDMS": { "Area": ["AB76", "AB77", "AB78"], "Type": ["PIPE", "BEND", "PIPESUP"] } }, limit=10) + >>> res = client.three_d.revisions.filter_nodes( + ... model_id=1, + ... revision_id=1, + ... properties={ + ... "PDMS": { + ... "Area": ["AB76", "AB77", "AB78"], + ... "Type": ["PIPE", "BEND", "PIPESUP"], + ... } + ... }, + ... limit=10, + ... ) """ resource_path = interpolate_and_url_encode(self._RESOURCE_PATH + "/{}/nodes", model_id, revision_id) return await self._list( @@ -352,7 +366,9 @@ async def list_ancestor_nodes( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.three_d.revisions.list_ancestor_nodes(model_id=1, revision_id=1, node_id=5, limit=10) + >>> res = client.three_d.revisions.list_ancestor_nodes( + ... model_id=1, revision_id=1, node_id=5, limit=10 + ... ) """ resource_path = interpolate_and_url_encode(self._RESOURCE_PATH + "/{}/nodes", model_id, revision_id) return await self._list( diff --git a/cognite/client/_api/time_series.py b/cognite/client/_api/time_series.py index b77c3ad9fb..2545fa71fc 100644 --- a/cognite/client/_api/time_series.py +++ b/cognite/client/_api/time_series.py @@ -334,7 +334,8 @@ async def aggregate_cardinality_values( >>> timezone_count = client.time_series.aggregate_cardinality_values( ... TimeSeriesProperty.metadata_key("timezone"), ... advanced_filter=is_critical, - ... aggregate_filter=not_america) + ... aggregate_filter=not_america, + ... ) """ self._validate_filter(advanced_filter) @@ -371,7 +372,9 @@ async def aggregate_cardinality_properties( >>> from cognite.client.data_classes.time_series import TimeSeriesProperty >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> key_count = client.time_series.aggregate_cardinality_properties(TimeSeriesProperty.metadata) + >>> key_count = client.time_series.aggregate_cardinality_properties( + ... TimeSeriesProperty.metadata + ... ) """ self._validate_filter(advanced_filter) return await self._advanced_aggregate( @@ -408,7 +411,9 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes.time_series import TimeSeriesProperty >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> result = client.time_series.aggregate_unique_values(TimeSeriesProperty.metadata_key("timezone")) + >>> result = client.time_series.aggregate_unique_values( + ... TimeSeriesProperty.metadata_key("timezone") + ... ) >>> print(result.unique) Get the different units with count used for time series created after 2020-01-01 in your CDF project: @@ -417,8 +422,12 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes.time_series import TimeSeriesProperty >>> from cognite.client.utils import timestamp_to_ms >>> from datetime import datetime - >>> created_after_2020 = filters.Range(TimeSeriesProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.time_series.aggregate_unique_values(TimeSeriesProperty.unit, advanced_filter=created_after_2020) + >>> created_after_2020 = filters.Range( + ... TimeSeriesProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.time_series.aggregate_unique_values( + ... TimeSeriesProperty.unit, advanced_filter=created_after_2020 + ... ) >>> print(result.unique) Get the different units with count for time series updated after 2020-01-01 in your CDF project, but exclude all units that @@ -427,8 +436,14 @@ async def aggregate_unique_values( >>> from cognite.client.data_classes.time_series import TimeSeriesProperty >>> from cognite.client.data_classes import aggregations as aggs, filters >>> not_test = aggs.Not(aggs.Prefix("test")) - >>> created_after_2020 = filters.Range(TimeSeriesProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.time_series.aggregate_unique_values(TimeSeriesProperty.unit, advanced_filter=created_after_2020, aggregate_filter=not_test) + >>> created_after_2020 = filters.Range( + ... TimeSeriesProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.time_series.aggregate_unique_values( + ... TimeSeriesProperty.unit, + ... advanced_filter=created_after_2020, + ... aggregate_filter=not_test, + ... ) >>> print(result.unique) """ self._validate_filter(advanced_filter) @@ -502,7 +517,9 @@ async def create( >>> from cognite.client.data_classes import TimeSeriesWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> ts = client.time_series.create(TimeSeriesWrite(name="my_ts", data_set_id=123, external_id="foo")) + >>> ts = client.time_series.create( + ... TimeSeriesWrite(name="my_ts", data_set_id=123, external_id="foo") + ... ) """ return await self._create_multiple( list_cls=TimeSeriesList, @@ -531,7 +548,7 @@ async def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.time_series.delete(id=[1,2,3], external_id="3") + >>> client.time_series.delete(id=[1, 2, 3], external_id="3") """ await self._delete_multiple( identifiers=IdentifierSequence.load(ids=id, external_ids=external_id), @@ -584,7 +601,11 @@ async def update( Perform a partial update on a time series, updating the description and adding a new field to metadata: >>> from cognite.client.data_classes import TimeSeriesUpdate - >>> my_update = TimeSeriesUpdate(id=1).description.set("New description").metadata.add({"key": "value"}) + >>> my_update = ( + ... TimeSeriesUpdate(id=1) + ... .description.set("New description") + ... .metadata.add({"key": "value"}) + ... ) >>> res = client.time_series.update(my_update) Perform a partial update on a time series by instance id. @@ -649,8 +670,12 @@ async def upsert( >>> # async_client = AsyncCogniteClient() # another option >>> existing_time_series = client.time_series.retrieve(id=1) >>> existing_time_series.description = "New description" - >>> new_time_series = TimeSeriesWrite(external_id="new_timeSeries", description="New timeSeries") - >>> res = client.time_series.upsert([existing_time_series, new_time_series], mode="replace") + >>> new_time_series = TimeSeriesWrite( + ... external_id="new_timeSeries", description="New timeSeries" + ... ) + >>> res = client.time_series.upsert( + ... [existing_time_series, new_time_series], mode="replace" + ... ) """ return await self._upsert_multiple( @@ -694,7 +719,7 @@ async def search( Search for all time series connected to asset with id 123: - >>> res = client.time_series.search(filter={"asset_ids":[123]}) + >>> res = client.time_series.search(filter={"asset_ids": [123]}) """ return await self._search( @@ -780,14 +805,16 @@ async def list( Iterate over chunks of time series to reduce memory load: >>> for ts_list in client.time_series(chunk_size=2500): - ... ts_list # do something with the time series + ... ts_list # do something with the time series Using advanced filter, find all time series that have a metadata key 'timezone' starting with 'Europe', and sort by external id ascending: >>> from cognite.client.data_classes import filters >>> in_timezone = filters.Prefix(["metadata", "timezone"], "Europe") - >>> res = client.time_series.list(advanced_filter=in_timezone, sort=("external_id", "asc")) + >>> res = client.time_series.list( + ... advanced_filter=in_timezone, sort=("external_id", "asc") + ... ) Note that you can check the API documentation above to see which properties you can filter on with which filters. @@ -796,20 +823,25 @@ async def list( for filtering and sorting, you can also use the `TimeSeriesProperty` and `SortableTimeSeriesProperty` Enums. >>> from cognite.client.data_classes import filters - >>> from cognite.client.data_classes.time_series import TimeSeriesProperty, SortableTimeSeriesProperty + >>> from cognite.client.data_classes.time_series import ( + ... TimeSeriesProperty, + ... SortableTimeSeriesProperty, + ... ) >>> in_timezone = filters.Prefix(TimeSeriesProperty.metadata_key("timezone"), "Europe") >>> res = client.time_series.list( - ... advanced_filter=in_timezone, - ... sort=(SortableTimeSeriesProperty.external_id, "asc")) + ... advanced_filter=in_timezone, sort=(SortableTimeSeriesProperty.external_id, "asc") + ... ) Combine filter and advanced filter: >>> from cognite.client.data_classes import filters >>> not_instrument_lvl5 = filters.And( - ... filters.ContainsAny("labels", ["Level5"]), - ... filters.Not(filters.ContainsAny("labels", ["Instrument"])) + ... filters.ContainsAny("labels", ["Level5"]), + ... filters.Not(filters.ContainsAny("labels", ["Instrument"])), + ... ) + >>> res = client.time_series.list( + ... asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5 ... ) - >>> res = client.time_series.list(asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5) """ asset_subtree_ids_processed = process_asset_subtree_ids(asset_subtree_ids, asset_subtree_external_ids) data_set_ids_processed = process_data_set_ids(data_set_ids, data_set_external_ids) diff --git a/cognite/client/_api/transformations/__init__.py b/cognite/client/_api/transformations/__init__.py index b5d9b3c5b8..5e426941a6 100644 --- a/cognite/client/_api/transformations/__init__.py +++ b/cognite/client/_api/transformations/__init__.py @@ -165,8 +165,15 @@ async def create( Create new transformations: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes import TransformationWrite, TransformationDestination - >>> from cognite.client.data_classes.transformations.common import ViewInfo, EdgeType, DataModelInfo + >>> from cognite.client.data_classes import ( + ... TransformationWrite, + ... TransformationDestination, + ... ) + >>> from cognite.client.data_classes.transformations.common import ( + ... ViewInfo, + ... EdgeType, + ... DataModelInfo, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> transformations = [ @@ -399,7 +406,9 @@ async def retrieve_multiple( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.transformations.retrieve_multiple(ids=[1,2,3], external_ids=['transform-1','transform-2']) + >>> res = client.transformations.retrieve_multiple( + ... ids=[1, 2, 3], external_ids=["transform-1", "transform-2"] + ... ) """ identifiers = IdentifierSequence.load(ids=ids, external_ids=external_ids) return await self._retrieve_multiple( @@ -454,7 +463,11 @@ async def update( Perform a partial update on a transformation, updating the query and making it private: >>> from cognite.client.data_classes import TransformationUpdate - >>> my_update = TransformationUpdate(id=1).query.set("SELECT * FROM _cdf.assets").is_public.set(False) + >>> my_update = ( + ... TransformationUpdate(id=1) + ... .query.set("SELECT * FROM _cdf.assets") + ... .is_public.set(False) + ... ) >>> res = client.transformations.update(my_update) Update the session used for reading (source) and writing (destination) when authenticating for all @@ -466,7 +479,7 @@ async def update( >>> new_nonce = NonceCredentials( ... session_id=new_session.id, ... nonce=new_session.nonce, - ... cdf_project_name=client.config.project + ... cdf_project_name=client.config.project, ... ) >>> for tr in to_update: ... tr.source_nonce = new_nonce @@ -614,12 +627,16 @@ async def preview( a query that converts one source row to one result row, you may need to increase the `source_limit`. For example, given that you have a query that reads from a raw table with 10,903 rows - >>> result = client.transformations.preview(query="select * from my_raw_db.my_raw_table", limit=None) + >>> result = client.transformations.preview( + ... query="select * from my_raw_db.my_raw_table", limit=None + ... ) >>> print(result.results) # 100 To get all rows, you also need to set the `source_limit` to None: - >>> result = client.transformations.preview(query="select * from my_raw_db.my_raw_table", limit=None, source_limit=None) + >>> result = client.transformations.preview( + ... query="select * from my_raw_db.my_raw_table", limit=None, source_limit=None + ... ) >>> print(result.results) # 10903 """ diff --git a/cognite/client/_api/transformations/notifications.py b/cognite/client/_api/transformations/notifications.py index ef575db363..188bd3a31e 100644 --- a/cognite/client/_api/transformations/notifications.py +++ b/cognite/client/_api/transformations/notifications.py @@ -182,6 +182,6 @@ async def delete(self, id: int | Sequence[int] | None = None) -> None: >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.transformations.notifications.delete(id=[1,2,3]) + >>> client.transformations.notifications.delete(id=[1, 2, 3]) """ await self._delete_multiple(identifiers=IdentifierSequence.load(ids=id), wrap_ids=True) diff --git a/cognite/client/_api/transformations/schedules.py b/cognite/client/_api/transformations/schedules.py index d84ba3d89c..d356535635 100644 --- a/cognite/client/_api/transformations/schedules.py +++ b/cognite/client/_api/transformations/schedules.py @@ -225,7 +225,7 @@ async def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.transformations.schedules.delete(id=[1,2,3], external_id="3") + >>> client.transformations.schedules.delete(id=[1, 2, 3], external_id="3") """ await self._delete_multiple( identifiers=IdentifierSequence.load(ids=id, external_ids=external_id), @@ -278,7 +278,9 @@ async def update( Perform a partial update on a transformation schedule, updating the interval and unpausing it: >>> from cognite.client.data_classes import TransformationScheduleUpdate - >>> my_update = TransformationScheduleUpdate(id=1).interval.set("0 * * * *").is_paused.set(False) + >>> my_update = ( + ... TransformationScheduleUpdate(id=1).interval.set("0 * * * *").is_paused.set(False) + ... ) >>> res = client.transformations.schedules.update(my_update) """ return await self._update_multiple( diff --git a/cognite/client/_api/units.py b/cognite/client/_api/units.py index e0f0ab80b9..ff92f5cd7d 100644 --- a/cognite/client/_api/units.py +++ b/cognite/client/_api/units.py @@ -67,11 +67,11 @@ async def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.units.retrieve('temperature:deg_c') + >>> res = client.units.retrieve("temperature:deg_c") Retrive units 'temperature:deg_c' and 'pressure:bar': - >>> res = client.units.retrieve(['temperature:deg_c', 'pressure:bar']) + >>> res = client.units.retrieve(["temperature:deg_c", "pressure:bar"]) """ identifier = IdentifierSequence.load(external_ids=external_id) @@ -137,11 +137,11 @@ async def from_alias( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> unit = client.units.from_alias('cmol / L') + >>> unit = client.units.from_alias("cmol / L") Look up ambiguous alias 'F' by passing quantity 'Temperature': - >>> unit = client.units.from_alias('F', 'Temperature') + >>> unit = client.units.from_alias("F", "Temperature") Search for the closest matching unit of 'kilo watt' (should be 'kilowatt'): diff --git a/cognite/client/_api/vision.py b/cognite/client/_api/vision.py index 9bf4ad58c5..996f5dacc3 100644 --- a/cognite/client/_api/vision.py +++ b/cognite/client/_api/vision.py @@ -68,7 +68,9 @@ async def extract( >>> from cognite.client.data_classes.contextualization import VisionFeature >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> extract_job = client.vision.extract(features=VisionFeature.ASSET_TAG_DETECTION, file_ids=[1]) + >>> extract_job = client.vision.extract( + ... features=VisionFeature.ASSET_TAG_DETECTION, file_ids=[1] + ... ) >>> extract_job.wait_for_completion() >>> for item in extract_job.items: ... predictions = item.predictions diff --git a/cognite/client/_api/workflows/executions.py b/cognite/client/_api/workflows/executions.py index e2f4a2f99e..e26564d7b9 100644 --- a/cognite/client/_api/workflows/executions.py +++ b/cognite/client/_api/workflows/executions.py @@ -41,7 +41,9 @@ async def retrieve_detailed(self, id: str) -> WorkflowExecutionDetailed | None: >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.workflows.executions.retrieve_detailed("000560bc-9080-4286-b242-a27bb4819253") + >>> res = client.workflows.executions.retrieve_detailed( + ... "000560bc-9080-4286-b242-a27bb4819253" + ... ) List workflow executions and retrieve detailed information for the first one: @@ -85,7 +87,9 @@ async def run( ... external_id="my_workflow-task1", ... parameters=FunctionTaskParameters( ... external_id="cdf_deployed_function:my_function", - ... data={"workflow_data": "${workflow.input}"})) + ... data={"workflow_data": "${workflow.input}"}, + ... ), + ... ) Tip: You can create a session via the Sessions API, using the client.iam.session.create() method. @@ -161,8 +165,7 @@ async def list( Get all workflow executions from the last 24 hours: >>> from cognite.client.utils import timestamp_to_ms - >>> res = client.workflows.executions.list( - ... created_time_start=timestamp_to_ms("1d-ago")) + >>> res = client.workflows.executions.list(created_time_start=timestamp_to_ms("1d-ago")) """ # Passing at least one filter criterion is required: diff --git a/cognite/client/_api/workflows/tasks.py b/cognite/client/_api/workflows/tasks.py index ed187fc762..03e478ec6f 100644 --- a/cognite/client/_api/workflows/tasks.py +++ b/cognite/client/_api/workflows/tasks.py @@ -34,11 +34,15 @@ async def update( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.workflows.tasks.update("000560bc-9080-4286-b242-a27bb4819253", "completed") + >>> res = client.workflows.tasks.update( + ... "000560bc-9080-4286-b242-a27bb4819253", "completed" + ... ) Update task with id '000560bc-9080-4286-b242-a27bb4819253' to status 'failed' with output '{"a": 1, "b": 2}': - >>> res = client.workflows.tasks.update("000560bc-9080-4286-b242-a27bb4819253", "failed", output={"a": 1, "b": 2}) + >>> res = client.workflows.tasks.update( + ... "000560bc-9080-4286-b242-a27bb4819253", "failed", output={"a": 1, "b": 2} + ... ) Trigger workflow, retrieve detailed task execution and update status of the second task (assumed to be async) to 'completed': diff --git a/cognite/client/_api/workflows/triggers.py b/cognite/client/_api/workflows/triggers.py index cb9c2a5519..464d5f11f8 100644 --- a/cognite/client/_api/workflows/triggers.py +++ b/cognite/client/_api/workflows/triggers.py @@ -47,14 +47,19 @@ async def upsert( Create or update a scheduled trigger for a workflow: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.workflows import WorkflowTriggerUpsert, WorkflowScheduledTriggerRule + >>> from cognite.client.data_classes.workflows import ( + ... WorkflowTriggerUpsert, + ... WorkflowScheduledTriggerRule, + ... ) >>> from zoneinfo import ZoneInfo >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> client.workflows.triggers.upsert( ... WorkflowTriggerUpsert( ... external_id="my_trigger", - ... trigger_rule=WorkflowScheduledTriggerRule(cron_expression="0 0 * * *", timezone=ZoneInfo("UTC")), + ... trigger_rule=WorkflowScheduledTriggerRule( + ... cron_expression="0 0 * * *", timezone=ZoneInfo("UTC") + ... ), ... workflow_external_id="my_workflow", ... workflow_version="1", ... input={"a": 1, "b": 2}, @@ -64,8 +69,15 @@ async def upsert( Create or update a data modeling trigger for a workflow: - >>> from cognite.client.data_classes.workflows import WorkflowDataModelingTriggerRule, WorkflowTriggerDataModelingQuery - >>> from cognite.client.data_classes.data_modeling.query import NodeResultSetExpression, Select, SourceSelector + >>> from cognite.client.data_classes.workflows import ( + ... WorkflowDataModelingTriggerRule, + ... WorkflowTriggerDataModelingQuery, + ... ) + >>> from cognite.client.data_classes.data_modeling.query import ( + ... NodeResultSetExpression, + ... Select, + ... SourceSelector, + ... ) >>> from cognite.client.data_classes.data_modeling import ViewId >>> from cognite.client.data_classes.filters import Equals >>> view_id = ViewId("my_space_id", "view_external_id", "v1") @@ -74,7 +86,13 @@ async def upsert( ... external_id="my_trigger", ... trigger_rule=WorkflowDataModelingTriggerRule( ... data_modeling_query=WorkflowTriggerDataModelingQuery( - ... with_={"timeseries": NodeResultSetExpression(filter=Equals(view_id.as_property_ref("name"), value="my_name"))}, + ... with_={ + ... "timeseries": NodeResultSetExpression( + ... filter=Equals( + ... view_id.as_property_ref("name"), value="my_name" + ... ) + ... ) + ... }, ... select={"timeseries": Select([SourceSelector(view_id, ["name"])])}, ... ), ... batch_size=500, diff --git a/cognite/client/_api/workflows/versions.py b/cognite/client/_api/workflows/versions.py index 7572635a1a..461aa95415 100644 --- a/cognite/client/_api/workflows/versions.py +++ b/cognite/client/_api/workflows/versions.py @@ -109,8 +109,10 @@ async def upsert( >>> from cognite.client import CogniteClient >>> from cognite.client.data_classes import ( - ... WorkflowVersionUpsert, WorkflowDefinitionUpsert, - ... WorkflowTask, FunctionTaskParameters, + ... WorkflowVersionUpsert, + ... WorkflowDefinitionUpsert, + ... WorkflowTask, + ... FunctionTaskParameters, ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option @@ -122,12 +124,12 @@ async def upsert( ... ), ... ) >>> new_version = WorkflowVersionUpsert( - ... workflow_external_id="my_workflow", - ... version="1", - ... workflow_definition=WorkflowDefinitionUpsert( - ... tasks=[function_task], - ... description="This workflow has one step", - ... ), + ... workflow_external_id="my_workflow", + ... version="1", + ... workflow_definition=WorkflowDefinitionUpsert( + ... tasks=[function_task], + ... description="This workflow has one step", + ... ), ... ) >>> res = client.workflows.versions.upsert(new_version) """ @@ -168,7 +170,9 @@ async def delete( Delete workflow version "1" of workflow "my workflow" and workflow version "2" of workflow "my workflow 2" using the WorkflowVersionId class: >>> from cognite.client.data_classes import WorkflowVersionId - >>> client.workflows.versions.delete([WorkflowVersionId("my workflow", "1"), WorkflowVersionId("my workflow 2", "2")]) + >>> client.workflows.versions.delete( + ... [WorkflowVersionId("my workflow", "1"), WorkflowVersionId("my workflow 2", "2")] + ... ) """ identifiers = WorkflowIds.load(workflow_version_id).dump(camel_case=True) @@ -282,12 +286,12 @@ async def list( >>> from cognite.client.data_classes import WorkflowVersionId >>> res = client.workflows.versions.list( - ... [WorkflowVersionId("my_workflow"), WorkflowVersionId("my_workflow_2")]) + ... [WorkflowVersionId("my_workflow"), WorkflowVersionId("my_workflow_2")] + ... ) Get all workflow versions for workflows 'my_workflow' version '1' and 'my_workflow_2' version '2' using tuples: - >>> res = client.workflows.versions.list( - ... [("my_workflow", "1"), ("my_workflow_2", "2")]) + >>> res = client.workflows.versions.list([("my_workflow", "1"), ("my_workflow_2", "2")]) """ return await self._list( diff --git a/cognite/client/_sync_api/agents/agents.py b/cognite/client/_sync_api/agents/agents.py index 5a49580ba4..4156e60861 100644 --- a/cognite/client/_sync_api/agents/agents.py +++ b/cognite/client/_sync_api/agents/agents.py @@ -52,10 +52,9 @@ def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | AgentLi ... AgentUpsert, ... QueryKnowledgeGraphAgentToolUpsert, ... QueryKnowledgeGraphAgentToolConfiguration, - ... DataModelInfo + ... DataModelInfo, ... ) >>> client = CogniteClient() - ... >>> find_assets_tool = QueryKnowledgeGraphAgentToolUpsert( ... name="find assets", ... description="Use this tool to find assets", @@ -68,13 +67,13 @@ def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | AgentLi ... view_external_ids=["CogniteAsset"], ... ) ... ] - ... ) + ... ), ... ) >>> agent = AgentUpsert( ... external_id="my_agent", ... name="My Agent", ... labels=["published"], - ... tools=[find_assets_tool] + ... tools=[find_assets_tool], ... ) >>> client.agents.upsert(agents=[agent]) @@ -87,9 +86,8 @@ def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | AgentLi ... DataModelInfo, ... SummarizeDocumentAgentToolUpsert, ... AskDocumentAgentToolUpsert, - ... QueryTimeSeriesDatapointsAgentToolUpsert + ... QueryTimeSeriesDatapointsAgentToolUpsert, ... ) - ... >>> find_assets_tool = QueryKnowledgeGraphAgentToolUpsert( ... name="find assets", ... description="Use this tool to query the knowledge graph for assets", @@ -102,7 +100,7 @@ def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | AgentLi ... view_external_ids=["CogniteAsset"], ... ) ... ] - ... ) + ... ), ... ) >>> find_files_tool = QueryKnowledgeGraphAgentToolUpsert( ... name="find files", @@ -116,7 +114,7 @@ def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | AgentLi ... view_external_ids=["CogniteFile"], ... ) ... ] - ... ) + ... ), ... ) >>> find_time_series_tool = QueryKnowledgeGraphAgentToolUpsert( ... name="find time series", @@ -130,19 +128,19 @@ def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | AgentLi ... view_external_ids=["CogniteTimeSeries"], ... ) ... ] - ... ) + ... ), ... ) >>> summarize_tool = SummarizeDocumentAgentToolUpsert( ... name="summarize document", - ... description="Use this tool to get a summary of a document" + ... description="Use this tool to get a summary of a document", ... ) >>> ask_doc_tool = AskDocumentAgentToolUpsert( ... name="ask document", - ... description="Use this tool to ask questions about specific documents" + ... description="Use this tool to ask questions about specific documents", ... ) >>> ts_tool = QueryTimeSeriesDatapointsAgentToolUpsert( ... name="query time series", - ... description="Use this tool to query time series data points" + ... description="Use this tool to query time series data points", ... ) >>> agent = AgentUpsert( ... external_id="my_agent", @@ -150,7 +148,14 @@ def upsert(self, agents: AgentUpsert | Sequence[AgentUpsert]) -> Agent | AgentLi ... description="An agent with many tools", ... instructions="You are a helpful assistant that can query knowledge graphs, summarize documents, answer questions about documents, and query time series data points.", ... labels=["published"], - ... tools=[find_assets_tool, find_files_tool, find_time_series_tool, summarize_tool, ask_doc_tool, ts_tool] + ... tools=[ + ... find_assets_tool, + ... find_files_tool, + ... find_time_series_tool, + ... summarize_tool, + ... ask_doc_tool, + ... ts_tool, + ... ], ... ) >>> client.agents.upsert(agents=[agent]) """ @@ -263,8 +268,7 @@ def chat( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> response = client.agents.chat( - ... agent_external_id="my_agent", - ... messages=Message("What can you help me with?") + ... agent_external_id="my_agent", messages=Message("What can you help me with?") ... ) >>> print(response.text) @@ -273,7 +277,7 @@ def chat( >>> follow_up = client.agents.chat( ... agent_external_id="my_agent", ... messages=Message("Tell me more about that"), - ... cursor=response.cursor + ... cursor=response.cursor, ... ) Send multiple messages at once: @@ -282,8 +286,8 @@ def chat( ... agent_external_id="my_agent", ... messages=[ ... Message("Help me find the 1st stage compressor."), - ... Message("Once you have found it, find related time series.") - ... ] + ... Message("Once you have found it, find related time series."), + ... ], ... ) Chat with client-side actions: @@ -298,13 +302,13 @@ def chat( ... "a": {"type": "number", "description": "First number"}, ... "b": {"type": "number", "description": "Second number"}, ... }, - ... "required": ["a", "b"] - ... } + ... "required": ["a", "b"], + ... }, ... ) >>> response = client.agents.chat( ... agent_external_id="my_agent", ... messages=Message("What is 42 plus 58?"), - ... actions=[add_numbers_action] + ... actions=[add_numbers_action], ... ) >>> if response.action_calls: ... for call in response.action_calls: @@ -314,11 +318,10 @@ def chat( ... response = client.agents.chat( ... agent_external_id="my_agent", ... messages=ClientToolResult( - ... action_id=call.action_id, - ... content=f"The result is {result}" + ... action_id=call.action_id, content=f"The result is {result}" ... ), ... cursor=response.cursor, - ... actions=[add_numbers_action] + ... actions=[add_numbers_action], ... ) """ return run_sync( diff --git a/cognite/client/_sync_api/ai/tools/documents.py b/cognite/client/_sync_api/ai/tools/documents.py index b03263dc90..b8fc629092 100644 --- a/cognite/client/_sync_api/ai/tools/documents.py +++ b/cognite/client/_sync_api/ai/tools/documents.py @@ -53,9 +53,7 @@ def summarize( You can also use external ID or instance ID: >>> from cognite.client.data_classes.data_modeling import NodeId - >>> client.ai.tools.documents.summarize( - ... instance_id=NodeId("my-space", "my-xid") - ... ) + >>> client.ai.tools.documents.summarize(instance_id=NodeId("my-space", "my-xid")) """ return run_sync( self.__async_client.ai.tools.documents.summarize(id=id, external_id=external_id, instance_id=instance_id) diff --git a/cognite/client/_sync_api/annotations.py b/cognite/client/_sync_api/annotations.py index e9a08b3dad..4073aed6b2 100644 --- a/cognite/client/_sync_api/annotations.py +++ b/cognite/client/_sync_api/annotations.py @@ -181,7 +181,9 @@ def list(self, filter: AnnotationFilter | dict, limit: int | None = DEFAULT_LIMI >>> from cognite.client.data_classes import AnnotationFilter >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> flt = AnnotationFilter(annotated_resource_type="file", annotated_resource_ids=[{"id": 123}]) + >>> flt = AnnotationFilter( + ... annotated_resource_type="file", annotated_resource_ids=[{"id": 123}] + ... ) >>> res = client.annotations.list(flt, limit=None) """ return run_sync(self.__async_client.annotations.list(filter=filter, limit=limit)) diff --git a/cognite/client/_sync_api/assets.py b/cognite/client/_sync_api/assets.py index eddacd0f22..fe142f7a68 100644 --- a/cognite/client/_sync_api/assets.py +++ b/cognite/client/_sync_api/assets.py @@ -222,7 +222,9 @@ def retrieve_multiple( Get assets by external id: - >>> res = client.assets.retrieve_multiple(external_ids=["abc", "def"], ignore_unknown_ids=True) + >>> res = client.assets.retrieve_multiple( + ... external_ids=["abc", "def"], ignore_unknown_ids=True + ... ) """ return run_sync( self.__async_client.assets.retrieve_multiple( @@ -303,8 +305,8 @@ def aggregate_cardinality_values( >>> from cognite.client.data_classes.assets import AssetProperty >>> is_critical = Search(AssetProperty.description, "critical") >>> critical_assets = client.assets.aggregate_cardinality_values( - ... AssetProperty.metadata_key("timezone"), - ... advanced_filter=is_critical) + ... AssetProperty.metadata_key("timezone"), advanced_filter=is_critical + ... ) """ return run_sync( self.__async_client.assets.aggregate_cardinality_values( @@ -377,7 +379,9 @@ def aggregate_unique_values( >>> from cognite.client.data_classes.assets import AssetProperty >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> result = client.assets.aggregate_unique_values(AssetProperty.metadata_key("timezone")) + >>> result = client.assets.aggregate_unique_values( + ... AssetProperty.metadata_key("timezone") + ... ) >>> print(result.unique) Get the different labels with count used for assets created after 2020-01-01 in your CDF project: @@ -386,8 +390,12 @@ def aggregate_unique_values( >>> from cognite.client.data_classes.assets import AssetProperty >>> from cognite.client.utils import timestamp_to_ms >>> from datetime import datetime - >>> created_after_2020 = filters.Range(AssetProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.assets.aggregate_unique_values(AssetProperty.labels, advanced_filter=created_after_2020) + >>> created_after_2020 = filters.Range( + ... AssetProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.assets.aggregate_unique_values( + ... AssetProperty.labels, advanced_filter=created_after_2020 + ... ) >>> print(result.unique) Get the different labels with count for assets updated after 2020-01-01 in your CDF project, but exclude all labels that @@ -397,8 +405,14 @@ def aggregate_unique_values( >>> from cognite.client.data_classes import aggregations >>> from cognite.client.data_classes import filters >>> not_test = aggregations.Not(aggregations.Prefix("test")) - >>> created_after_2020 = filters.Range(AssetProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.assets.aggregate_unique_values(AssetProperty.labels, advanced_filter=created_after_2020, aggregate_filter=not_test) + >>> created_after_2020 = filters.Range( + ... AssetProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.assets.aggregate_unique_values( + ... AssetProperty.labels, + ... advanced_filter=created_after_2020, + ... aggregate_filter=not_test, + ... ) >>> print(result.unique) """ return run_sync( @@ -548,7 +562,8 @@ def create_hierarchy( >>> assets = [ ... AssetWrite(external_id="root", name="root"), ... AssetWrite(external_id="child1", parent_external_id="root", name="child1"), - ... AssetWrite(external_id="child2", parent_external_id="root", name="child2")] + ... AssetWrite(external_id="child2", parent_external_id="root", name="child2"), + ... ] >>> res = client.assets.create_hierarchy(assets) Create an asset hierarchy, but run update for existing assets: @@ -636,7 +651,7 @@ def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.assets.delete(id=[1,2,3], external_id="3") + >>> client.assets.delete(id=[1, 2, 3], external_id="3") """ return run_sync( self.__async_client.assets.delete( @@ -680,7 +695,11 @@ def update( >>> from cognite.client.data_classes import AssetUpdate >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> my_update = AssetUpdate(id=1).description.set("New description").metadata.add({"key": "value"}) + >>> my_update = ( + ... AssetUpdate(id=1) + ... .description.set("New description") + ... .metadata.add({"key": "value"}) + ... ) >>> res1 = client.assets.update(my_update) >>> # Remove an already set field like so >>> another_update = AssetUpdate(id=1).description.set(None) @@ -749,7 +768,9 @@ def upsert( >>> # async_client = AsyncCogniteClient() # another option >>> existing_asset = client.assets.retrieve(id=1) >>> existing_asset.description = "New description" - >>> new_asset = AssetWrite(external_id="new_asset", name="my asset", description="New asset") + >>> new_asset = AssetWrite( + ... external_id="new_asset", name="my asset", description="New asset" + ... ) >>> res = client.assets.upsert([existing_asset, new_asset], mode="replace") """ return run_sync(self.__async_client.assets.upsert(item=item, mode=mode)) @@ -795,12 +816,14 @@ def search( Search for assets using multiple filters, finding all assets with name similar to `xyz` with parent asset `123` or `456` with source `some source`: - >>> res = client.assets.search(name="xyz",filter={"parent_ids": [123,456],"source": "some source"}) + >>> res = client.assets.search( + ... name="xyz", filter={"parent_ids": [123, 456], "source": "some source"} + ... ) Search for an asset with an attached label: >>> my_label_filter = LabelFilter(contains_all=["PUMP"]) - >>> res = client.assets.search(name="xyz",filter=AssetFilter(labels=my_label_filter)) + >>> res = client.assets.search(name="xyz", filter=AssetFilter(labels=my_label_filter)) """ return run_sync( self.__async_client.assets.search( @@ -898,7 +921,7 @@ def list( Iterate over chunks of assets to reduce memory load: >>> for asset_list in client.assets(chunk_size=2500): - ... asset_list # do something with the assets + ... asset_list # do something with the assets Filter assets based on labels: @@ -923,17 +946,19 @@ def list( >>> from cognite.client.data_classes.assets import AssetProperty, SortableAssetProperty >>> in_timezone = filters.Prefix(AssetProperty.metadata_key("timezone"), "Europe") >>> res = client.assets.list( - ... advanced_filter=in_timezone, - ... sort=(SortableAssetProperty.external_id, "asc")) + ... advanced_filter=in_timezone, sort=(SortableAssetProperty.external_id, "asc") + ... ) Combine filter and advanced filter: >>> from cognite.client.data_classes import filters >>> not_instrument_lvl5 = filters.And( - ... filters.ContainsAny("labels", ["Level5"]), - ... filters.Not(filters.ContainsAny("labels", ["Instrument"])) + ... filters.ContainsAny("labels", ["Level5"]), + ... filters.Not(filters.ContainsAny("labels", ["Instrument"])), + ... ) + >>> res = client.assets.list( + ... asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5 ... ) - >>> res = client.assets.list(asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5) """ return run_sync( self.__async_client.assets.list( diff --git a/cognite/client/_sync_api/data_modeling/containers.py b/cognite/client/_sync_api/data_modeling/containers.py index daff01887f..91ed7802c5 100644 --- a/cognite/client/_sync_api/data_modeling/containers.py +++ b/cognite/client/_sync_api/data_modeling/containers.py @@ -94,13 +94,14 @@ def retrieve(self, ids: ContainerIdentifier | Sequence[ContainerIdentifier]) -> >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.data_modeling.containers.retrieve(('mySpace', 'myContainer')) + >>> res = client.data_modeling.containers.retrieve(("mySpace", "myContainer")) Fetch using the ContainerId: >>> from cognite.client.data_classes.data_modeling import ContainerId >>> res = client.data_modeling.containers.retrieve( - ... ContainerId(space='mySpace', external_id='myContainer')) + ... ContainerId(space="mySpace", external_id="myContainer") + ... ) """ return run_sync(self.__async_client.data_modeling.containers.retrieve(ids=ids)) @@ -199,7 +200,7 @@ def list( Iterate over chunks of containers to reduce memory load: >>> for container_list in client.data_modeling.containers(chunk_size=10): - ... container_list # do something with the containers + ... container_list # do something with the containers """ return run_sync( self.__async_client.data_modeling.containers.list(space=space, limit=limit, include_global=include_global) @@ -227,20 +228,26 @@ def apply(self, container: ContainerApply | Sequence[ContainerApply]) -> Contain >>> from cognite.client import CogniteClient >>> from cognite.client.data_classes.data_modeling import ( - ... ContainerApply, ContainerPropertyApply, Text, Float64) + ... ContainerApply, + ... ContainerPropertyApply, + ... Text, + ... Float64, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> container = ContainerApply( - ... space="mySpace", - ... external_id="myContainer", - ... properties={ - ... "name": ContainerPropertyApply(type=Text, name="name"), - ... "numbers": ContainerPropertyApply( - ... type=Float64(is_list=True, max_list_size=200), - ... description="very important numbers", - ... ), - ... }, - ... ), + >>> container = ( + ... ContainerApply( + ... space="mySpace", + ... external_id="myContainer", + ... properties={ + ... "name": ContainerPropertyApply(type=Text, name="name"), + ... "numbers": ContainerPropertyApply( + ... type=Float64(is_list=True, max_list_size=200), + ... description="very important numbers", + ... ), + ... }, + ... ), + ... ) >>> res = client.data_modeling.containers.apply(container) Create new container with unit-aware properties: @@ -256,11 +263,8 @@ def apply(self, container: ContainerApply | Sequence[ContainerApply]) -> Contain ... description="Maximum Pump Pressure", ... name="maxPressure", ... type=Float64( - ... unit=UnitReference( - ... external_id="pressure:bar", - ... source_unit="BAR" - ... ) - ... ) + ... unit=UnitReference(external_id="pressure:bar", source_unit="BAR") + ... ), ... ), ... "rotationConfigurations": ContainerPropertyApply( ... nullable=True, @@ -268,12 +272,10 @@ def apply(self, container: ContainerApply | Sequence[ContainerApply]) -> Contain ... name="rotationConfigurations", ... type=Float64( ... is_list=True, - ... unit=UnitReference( - ... external_id="angular_velocity:rev-per-min" - ... ) - ... ) - ... ) - ... } + ... unit=UnitReference(external_id="angular_velocity:rev-per-min"), + ... ), + ... ), + ... }, ... ) >>> res = client.data_modeling.containers.apply(container) @@ -282,10 +284,25 @@ def apply(self, container: ContainerApply | Sequence[ContainerApply]) -> Contain ``nullable``, ``auto_increment``, ``default_value`` and ``immutable`` that may be specified, depending on the choice of property type (e.g. ``auto_increment`` only works with integer types). - >>> from cognite.client.data_classes.data_modeling.data_types import UnitReference, EnumValue >>> from cognite.client.data_classes.data_modeling.data_types import ( - ... Boolean, Date, DirectRelation, Enum, FileReference, Float32, Float64, - ... Int32, Int64, Json, SequenceReference, Text, TimeSeriesReference, Timestamp + ... UnitReference, + ... EnumValue, + ... ) + >>> from cognite.client.data_classes.data_modeling.data_types import ( + ... Boolean, + ... Date, + ... DirectRelation, + ... Enum, + ... FileReference, + ... Float32, + ... Float64, + ... Int32, + ... Int64, + ... Json, + ... SequenceReference, + ... Text, + ... TimeSeriesReference, + ... Timestamp, ... ) >>> container_properties = { ... "prop01": ContainerPropertyApply(Boolean), @@ -302,8 +319,13 @@ def apply(self, container: ContainerApply | Sequence[ContainerApply]) -> Contain ... "prop10": ContainerPropertyApply(DirectRelation(is_list=True)), ... # Note: Enum also support `unknown_value`: The value to use when the enum value is unknown. ... "prop11": ContainerPropertyApply( - ... Enum({"Closed": EnumValue("Valve is closed"), - ... "Opened": EnumValue("Valve is opened")})), + ... Enum( + ... { + ... "Closed": EnumValue("Valve is closed"), + ... "Opened": EnumValue("Valve is opened"), + ... } + ... ) + ... ), ... # Note: Floats support unit references, e.g. `unit=UnitReference("pressure:bar")`: ... "prop12": ContainerPropertyApply(Float32), ... "prop13": ContainerPropertyApply(Float32(is_list=True)), diff --git a/cognite/client/_sync_api/data_modeling/data_models.py b/cognite/client/_sync_api/data_modeling/data_models.py index 436ad06069..7fb1e94416 100644 --- a/cognite/client/_sync_api/data_modeling/data_models.py +++ b/cognite/client/_sync_api/data_modeling/data_models.py @@ -203,7 +203,7 @@ def list( Iterate over chunks of data model to reduce memory load: >>> for data_model_list in client.data_modeling.data_models(chunk_size=10): - ... data_model_list # do something with the data model + ... data_model_list # do something with the data model """ return run_sync( self.__async_client.data_modeling.data_models.list( # type: ignore [call-overload] @@ -240,8 +240,19 @@ def apply(self, data_model: DataModelApply | Sequence[DataModelApply]) -> DataMo >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> data_models = [ - ... DataModelApply(space="mySpace",external_id="myDataModel",version="v1",views=[ViewId("mySpace","myView","v1")]), - ... DataModelApply(space="mySpace",external_id="myOtherDataModel",version="v1",views=[ViewId("mySpace","myView","v1")])] + ... DataModelApply( + ... space="mySpace", + ... external_id="myDataModel", + ... version="v1", + ... views=[ViewId("mySpace", "myView", "v1")], + ... ), + ... DataModelApply( + ... space="mySpace", + ... external_id="myOtherDataModel", + ... version="v1", + ... views=[ViewId("mySpace", "myView", "v1")], + ... ), + ... ] >>> res = client.data_modeling.data_models.apply(data_models) """ return run_sync(self.__async_client.data_modeling.data_models.apply(data_model=data_model)) diff --git a/cognite/client/_sync_api/data_modeling/graphql.py b/cognite/client/_sync_api/data_modeling/graphql.py index 42de32af04..6ead37f2c3 100644 --- a/cognite/client/_sync_api/data_modeling/graphql.py +++ b/cognite/client/_sync_api/data_modeling/graphql.py @@ -69,7 +69,7 @@ def apply_dml( ... id=("mySpaceExternalId", "myModelExternalId", "1"), ... dml="type MyType { id: String! }", ... name="My model name", - ... description="My model description" + ... description="My model description", ... ) """ return run_sync( diff --git a/cognite/client/_sync_api/data_modeling/instances.py b/cognite/client/_sync_api/data_modeling/instances.py index 305a63a492..d02b5eb574 100644 --- a/cognite/client/_sync_api/data_modeling/instances.py +++ b/cognite/client/_sync_api/data_modeling/instances.py @@ -215,32 +215,45 @@ def retrieve_edges( We strongly suggest you use snake_cased attribute names, as is done here: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.data_modeling import EdgeId, TypedEdge, PropertyOptions, DirectRelationReference, ViewId + >>> from cognite.client.data_classes.data_modeling import ( + ... EdgeId, + ... TypedEdge, + ... PropertyOptions, + ... DirectRelationReference, + ... ViewId, + ... ) >>> class Flow(TypedEdge): - ... flow_rate = PropertyOptions(identifier="flowRate") - ... - ... def __init__( - ... self, - ... space: str, - ... external_id: str, - ... version: int, - ... type: DirectRelationReference, - ... last_updated_time: int, - ... created_time: int, - ... flow_rate: float, - ... start_node: DirectRelationReference, - ... end_node: DirectRelationReference, - ... deleted_time: int | None = None, - ... ) -> None: - ... super().__init__( - ... space, external_id, version, type, last_updated_time, created_time, start_node, end_node, deleted_time - ... ) - ... self.flow_rate = flow_rate + ... flow_rate = PropertyOptions(identifier="flowRate") ... - ... @classmethod - ... def get_source(cls) -> ViewId: - ... return ViewId("sp_model_space", "flow", "1") + ... def __init__( + ... self, + ... space: str, + ... external_id: str, + ... version: int, + ... type: DirectRelationReference, + ... last_updated_time: int, + ... created_time: int, + ... flow_rate: float, + ... start_node: DirectRelationReference, + ... end_node: DirectRelationReference, + ... deleted_time: int | None = None, + ... ) -> None: + ... super().__init__( + ... space, + ... external_id, + ... version, + ... type, + ... last_updated_time, + ... created_time, + ... start_node, + ... end_node, + ... deleted_time, + ... ) + ... self.flow_rate = flow_rate ... + ... @classmethod + ... def get_source(cls) -> ViewId: + ... return ViewId("sp_model_space", "flow", "1") >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> res = client.data_modeling.instances.retrieve_edges( @@ -311,38 +324,43 @@ def retrieve_nodes( We strongly suggest you use snake_cased attribute names, as is done here: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.data_modeling import NodeId, TypedNode, PropertyOptions, DirectRelationReference, ViewId + >>> from cognite.client.data_classes.data_modeling import ( + ... NodeId, + ... TypedNode, + ... PropertyOptions, + ... DirectRelationReference, + ... ViewId, + ... ) >>> class Person(TypedNode): - ... birth_year = PropertyOptions(identifier="birthYear") - ... - ... def __init__( - ... self, - ... space: str, - ... external_id: str, - ... version: int, - ... last_updated_time: int, - ... created_time: int, - ... name: str, - ... birth_year: int | None = None, - ... type: DirectRelationReference | None = None, - ... deleted_time: int | None = None, - ... ): - ... super().__init__( - ... space=space, - ... external_id=external_id, - ... version=version, - ... last_updated_time=last_updated_time, - ... created_time=created_time, - ... type=type, - ... deleted_time=deleted_time - ... ) - ... self.name = name - ... self.birth_year = birth_year + ... birth_year = PropertyOptions(identifier="birthYear") ... - ... @classmethod - ... def get_source(cls) -> ViewId: - ... return ViewId("myModelSpace", "Person", "1") + ... def __init__( + ... self, + ... space: str, + ... external_id: str, + ... version: int, + ... last_updated_time: int, + ... created_time: int, + ... name: str, + ... birth_year: int | None = None, + ... type: DirectRelationReference | None = None, + ... deleted_time: int | None = None, + ... ): + ... super().__init__( + ... space=space, + ... external_id=external_id, + ... version=version, + ... last_updated_time=last_updated_time, + ... created_time=created_time, + ... type=type, + ... deleted_time=deleted_time, + ... ) + ... self.name = name + ... self.birth_year = birth_year ... + ... @classmethod + ... def get_source(cls) -> ViewId: + ... return ViewId("myModelSpace", "Person", "1") >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> res = client.data_modeling.instances.retrieve_nodes( @@ -385,7 +403,8 @@ def retrieve( >>> res = client.data_modeling.instances.retrieve( ... nodes=("mySpace", "myNodeExternalId"), ... edges=("mySpace", "myEdgeExternalId"), - ... sources=("mySpace", "myViewExternalId", "myViewVersion")) + ... sources=("mySpace", "myViewExternalId", "myViewVersion"), + ... ) Retrieve nodes an edges using the built in data class @@ -393,7 +412,8 @@ def retrieve( >>> res = client.data_modeling.instances.retrieve( ... NodeId("mySpace", "myNode"), ... EdgeId("mySpace", "myEdge"), - ... ViewId("mySpace", "myViewExternalId", "myViewVersion")) + ... ViewId("mySpace", "myViewExternalId", "myViewVersion"), + ... ) Retrieve nodes an edges using the the view object as source @@ -401,7 +421,8 @@ def retrieve( >>> res = client.data_modeling.instances.retrieve( ... NodeId("mySpace", "myNode"), ... EdgeId("mySpace", "myEdge"), - ... sources=("myspace", "myView")) + ... sources=("myspace", "myView"), + ... ) """ return run_sync( self.__async_client.data_modeling.instances.retrieve( @@ -436,13 +457,17 @@ def delete( Delete nodes and edges using the built in data class >>> from cognite.client.data_classes.data_modeling import NodeId, EdgeId - >>> client.data_modeling.instances.delete(NodeId('mySpace', 'myNode'), EdgeId('mySpace', 'myEdge')) + >>> client.data_modeling.instances.delete( + ... NodeId("mySpace", "myNode"), EdgeId("mySpace", "myEdge") + ... ) Delete all nodes from a NodeList >>> from cognite.client.data_classes.data_modeling import NodeId, EdgeId - >>> my_view = client.data_modeling.views.retrieve(('mySpace', 'myView')) - >>> my_nodes = client.data_modeling.instances.list(instance_type='node', sources=my_view, limit=None) + >>> my_view = client.data_modeling.views.retrieve(("mySpace", "myView")) + >>> my_nodes = client.data_modeling.instances.list( + ... instance_type="node", sources=my_view, limit=None + ... ) >>> client.data_modeling.instances.delete(nodes=my_nodes.as_ids()) """ return run_sync(self.__async_client.data_modeling.instances.delete(nodes=nodes, edges=edges)) @@ -528,7 +553,11 @@ def subscribe( >>> from cognite.client import CogniteClient >>> from cognite.client.data_classes.data_modeling.query import ( - ... QuerySync, QueryResult, NodeResultSetExpressionSync, SelectSync, SourceSelector + ... QuerySync, + ... QueryResult, + ... NodeResultSetExpressionSync, + ... SelectSync, + ... SourceSelector, ... ) >>> from cognite.client.data_classes.data_modeling import ViewId >>> from cognite.client.data_classes.filters import Equals @@ -541,7 +570,7 @@ def subscribe( >>> filter = Equals(view_id.as_property_ref("myAsset"), "Il-Tempo-Gigante") >>> query = QuerySync( ... with_={"work_orders": NodeResultSetExpressionSync(filter=filter)}, - ... select={"work_orders": SelectSync([SourceSelector(view_id, ["*"])])} + ... select={"work_orders": SelectSync([SourceSelector(view_id, ["*"])])}, ... ) >>> subscription_context = client.data_modeling.instances.subscribe( ... query, callback=just_print_the_result @@ -584,7 +613,11 @@ def apply( Create new node without data: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.data_modeling import EdgeApply, NodeOrEdgeData, NodeApply + >>> from cognite.client.data_classes.data_modeling import ( + ... EdgeApply, + ... NodeOrEdgeData, + ... NodeApply, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> node = NodeApply("mySpace", "myNodeId") @@ -592,7 +625,13 @@ def apply( Create two nodes with data with a one-to-many edge - >>> from cognite.client.data_classes.data_modeling import ContainerId, EdgeApply, NodeOrEdgeData, NodeApply, ViewId + >>> from cognite.client.data_classes.data_modeling import ( + ... ContainerId, + ... EdgeApply, + ... NodeOrEdgeData, + ... NodeApply, + ... ViewId, + ... ) >>> work_order = NodeApply( ... space="industrial", ... external_id="work_order:123", @@ -600,9 +639,9 @@ def apply( ... # Insert data through a view ... NodeOrEdgeData( ... ViewId("mySpace", "WorkOrderView", "v1"), - ... {"title": "Repair pump", "createdYear": 2023} + ... {"title": "Repair pump", "createdYear": 2023}, ... ) - ... ] + ... ], ... ) >>> pump = NodeApply( ... space="industrial", @@ -611,9 +650,9 @@ def apply( ... # Insert data directly to the container ... NodeOrEdgeData( ... ContainerId("mySpace", "PumpContainer"), - ... {"name": "Pump 456", "location": "Subsea"} + ... {"name": "Pump 456", "location": "Subsea"}, ... ) - ... ] + ... ], ... ) ... # This is one-to-many edge, in this case from a work order to a pump >>> work_order_to_pump = EdgeApply( @@ -638,7 +677,7 @@ def apply( >>> res = client.data_modeling.instances.apply( ... edges=work_order_to_pump, ... auto_create_start_nodes=True, - ... auto_create_end_nodes=True + ... auto_create_end_nodes=True, ... ) Using helper function to create valid graphql timestamp for a datetime object: @@ -646,7 +685,9 @@ def apply( >>> from cognite.client.utils import datetime_to_ms_iso_timestamp >>> from datetime import datetime, timezone >>> my_date = datetime(2020, 3, 14, 15, 9, 26, 535000, tzinfo=timezone.utc) - >>> data_model_timestamp = datetime_to_ms_iso_timestamp(my_date) # "2020-03-14T15:09:26.535+00:00" + >>> data_model_timestamp = datetime_to_ms_iso_timestamp( + ... my_date + ... ) # "2020-03-14T15:09:26.535+00:00" Create a typed node apply. Any property that you want to look up by a different attribute name, e.g. you want `my_node.birth_year` to return the data for property `birthYear`, must use the PropertyOptions as shown below. @@ -660,9 +701,9 @@ def apply( ... super().__init__(space, external_id, type=("sp_model_space", "Person")) ... self.name = name ... self.birth_year = birth_year + ... ... def get_source(self): ... return ViewId("sp_model_space", "Person", "v1") - ... >>> person = PersonApply("sp_date_space", "my_person", "John Doe", 1980) >>> res = client.data_modeling.instances.apply(nodes=person) """ @@ -794,10 +835,7 @@ def search( >>> # async_client = AsyncCogniteClient() # another option >>> view = ViewId("assetSpace", "EquipmentView", "v1") >>> res = client.data_modeling.instances.search( - ... view, - ... query="centrifugal pump", - ... properties=["description"], - ... operator="AND" + ... view, query="centrifugal pump", properties=["description"], operator="AND" ... ) Search for 'pump', 'valve' or 'compressor', but filter on those installed after 2015: @@ -813,7 +851,7 @@ def search( ... query="pump valve compressor", ... properties=["name", "description"], ... filter=installed_after_2015, - ... operator="OR" + ... operator="OR", ... ) """ return run_sync( @@ -920,7 +958,9 @@ def aggregate( >>> # async_client = AsyncCogniteClient() # another option >>> avg_run_time = Average("runTimeMinutes") >>> view_id = ViewId("mySpace", "PumpView", "v1") - >>> res = client.data_modeling.instances.aggregate(view_id, avg_run_time, group_by="releaseYear") + >>> res = client.data_modeling.instances.aggregate( + ... view_id, avg_run_time, group_by="releaseYear" + ... ) """ return run_sync( self.__async_client.data_modeling.instances.aggregate( @@ -1041,7 +1081,13 @@ def query(self, query: Query, include_typing: bool = False, debug: DebugParamete Find work orders created before 2023 sorted by title: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.data_modeling.query import Query, Select, NodeResultSetExpression, EdgeResultSetExpression, SourceSelector + >>> from cognite.client.data_classes.data_modeling.query import ( + ... Query, + ... Select, + ... NodeResultSetExpression, + ... EdgeResultSetExpression, + ... SourceSelector, + ... ) >>> from cognite.client.data_classes.filters import Range, Equals >>> from cognite.client.data_classes.data_modeling.ids import ViewId >>> client = CogniteClient() @@ -1049,14 +1095,24 @@ def query(self, query: Query, include_typing: bool = False, debug: DebugParamete >>> work_order_id = ViewId("mySpace", "WorkOrderView", "v1") >>> pump_id = ViewId("mySpace", "PumpView", "v1") >>> query = Query( - ... with_ = { - ... "work_orders": NodeResultSetExpression(filter=Range(work_order_id.as_property_ref("createdYear"), lt=2023)), - ... "work_orders_to_pumps": EdgeResultSetExpression(from_="work_orders", filter=Equals(["edge", "type"], {"space": work_order_id.space, "externalId": "WorkOrder.asset"})), + ... with_={ + ... "work_orders": NodeResultSetExpression( + ... filter=Range(work_order_id.as_property_ref("createdYear"), lt=2023) + ... ), + ... "work_orders_to_pumps": EdgeResultSetExpression( + ... from_="work_orders", + ... filter=Equals( + ... ["edge", "type"], + ... {"space": work_order_id.space, "externalId": "WorkOrder.asset"}, + ... ), + ... ), ... "pumps": NodeResultSetExpression(from_="work_orders_to_pumps"), ... }, - ... select = { + ... select={ ... "pumps": Select( - ... [SourceSelector(pump_id, ["name"])], sort=[InstanceSort(pump_id.as_property_ref("name"))]), + ... [SourceSelector(pump_id, ["name"])], + ... sort=[InstanceSort(pump_id.as_property_ref("name"))], + ... ), ... }, ... ) >>> res = client.data_modeling.instances.query(query) @@ -1065,7 +1121,10 @@ def query(self, query: Query, include_typing: bool = False, debug: DebugParamete a UnitReference or a UnitSystemReference. Note that in order for a property to be converted, they need to have a unit defined in the underlying container. - >>> from cognite.client.data_classes.data_modeling.data_types import UnitReference, UnitSystemReference + >>> from cognite.client.data_classes.data_modeling.data_types import ( + ... UnitReference, + ... UnitSystemReference, + ... ) >>> selected_source = SourceSelector( ... source=ViewId("my-space", "my-xid", "v1"), ... properties=["f32_prop1", "f32_prop2", "f64_prop1", "f64_prop2"], @@ -1117,7 +1176,13 @@ def sync(self, query: QuerySync, include_typing: bool = False, debug: DebugParam >>> from cognite.client import CogniteClient >>> from cognite.client.data_classes.data_modeling.instances import InstanceSort - >>> from cognite.client.data_classes.data_modeling.query import Query, Select, NodeResultSetExpression, EdgeResultSetExpression, SourceSelector + >>> from cognite.client.data_classes.data_modeling.query import ( + ... Query, + ... Select, + ... NodeResultSetExpression, + ... EdgeResultSetExpression, + ... SourceSelector, + ... ) >>> from cognite.client.data_classes.filters import Range, Equals >>> from cognite.client.data_classes.data_modeling.ids import ViewId >>> client = CogniteClient() @@ -1125,14 +1190,24 @@ def sync(self, query: QuerySync, include_typing: bool = False, debug: DebugParam >>> work_order_id = ViewId("mySpace", "WorkOrderView", "v1") >>> pump_id = ViewId("mySpace", "PumpView", "v1") >>> query = Query( - ... with_ = { - ... "work_orders": NodeResultSetExpression(filter=Range(work_order_id.as_property_ref("createdYear"), lt=2023)), - ... "work_orders_to_pumps": EdgeResultSetExpression(from_="work_orders", filter=Equals(["edge", "type"], {"space": work_order_id.space, "externalId": "WorkOrder.asset"})), + ... with_={ + ... "work_orders": NodeResultSetExpression( + ... filter=Range(work_order_id.as_property_ref("createdYear"), lt=2023) + ... ), + ... "work_orders_to_pumps": EdgeResultSetExpression( + ... from_="work_orders", + ... filter=Equals( + ... ["edge", "type"], + ... {"space": work_order_id.space, "externalId": "WorkOrder.asset"}, + ... ), + ... ), ... "pumps": NodeResultSetExpression(from_="work_orders_to_pumps"), ... }, - ... select = { + ... select={ ... "pumps": Select( - ... [SourceSelector(pump_id, ["name"])], sort=[InstanceSort(pump_id.as_property_ref("name"))]), + ... [SourceSelector(pump_id, ["name"])], + ... sort=[InstanceSort(pump_id.as_property_ref("name"))], + ... ), ... }, ... ) >>> res = client.data_modeling.instances.sync(query) @@ -1252,9 +1327,10 @@ def list( >>> from cognite.client.data_classes.data_modeling import InstanceSort >>> property_sort = InstanceSort( - ... property=('space', 'view_xid/view_version', 'some_property'), + ... property=("space", "view_xid/view_version", "some_property"), ... direction="descending", - ... nulls_first=True) + ... nulls_first=True, + ... ) >>> instance_list = client.data_modeling.instances.list(sort=property_sort) Iterate over instances (nodes by default), one-by-one: @@ -1267,7 +1343,7 @@ def list( Iterate over chunks of instances to reduce memory load: >>> for instance_list in client.data_modeling.instances(chunk_size=100): - ... instance_list # do something with the instances + ... instance_list # do something with the instances List instances with a view as source: @@ -1293,9 +1369,7 @@ def list( ... include_translated_query=True, # Include the internal representation of the query. ... profile=True, ... ) - >>> res = client.data_modeling.instances.list( - ... debug=debug_params, sources=my_view - ... ) + >>> res = client.data_modeling.instances.list(debug=debug_params, sources=my_view) >>> print(res.debug) """ return run_sync( diff --git a/cognite/client/_sync_api/data_modeling/space_statistics.py b/cognite/client/_sync_api/data_modeling/space_statistics.py index 645dd63fac..88351f2721 100644 --- a/cognite/client/_sync_api/data_modeling/space_statistics.py +++ b/cognite/client/_sync_api/data_modeling/space_statistics.py @@ -51,9 +51,7 @@ def retrieve(self, space: str | SequenceNotStr[str]) -> SpaceStatistics | SpaceS >>> result = client.data_modeling.statistics.spaces.retrieve("my-space") Fetch statistics for multiple spaces: - >>> res = client.data_modeling.statistics.spaces.retrieve( - ... ["my-space1", "my-space2"] - ... ) + >>> res = client.data_modeling.statistics.spaces.retrieve(["my-space1", "my-space2"]) """ return run_sync(self.__async_client.data_modeling.statistics.spaces.retrieve(space=space)) diff --git a/cognite/client/_sync_api/data_modeling/spaces.py b/cognite/client/_sync_api/data_modeling/spaces.py index a26ebab140..aa3c3f092d 100644 --- a/cognite/client/_sync_api/data_modeling/spaces.py +++ b/cognite/client/_sync_api/data_modeling/spaces.py @@ -71,11 +71,13 @@ def retrieve(self, spaces: str | SequenceNotStr[str]) -> Space | SpaceList | Non >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.data_modeling.spaces.retrieve(spaces='mySpace') + >>> res = client.data_modeling.spaces.retrieve(spaces="mySpace") Get multiple spaces by id: - >>> res = client.data_modeling.spaces.retrieve(spaces=["MySpace", "MyAwesomeSpace", "MyOtherSpace"]) + >>> res = client.data_modeling.spaces.retrieve( + ... spaces=["MySpace", "MyAwesomeSpace", "MyOtherSpace"] + ... ) """ return run_sync(self.__async_client.data_modeling.spaces.retrieve(spaces=spaces)) @@ -126,7 +128,7 @@ def list(self, limit: int | None = DEFAULT_LIMIT_READ, include_global: bool = Fa Iterate over chunks of spaces to reduce memory load: >>> for space_list in client.data_modeling.spaces(chunk_size=2500): - ... space_list # do something with the spaces + ... space_list # do something with the spaces """ return run_sync(self.__async_client.data_modeling.spaces.list(limit=limit, include_global=include_global)) @@ -154,8 +156,12 @@ def apply(self, spaces: SpaceApply | Sequence[SpaceApply]) -> Space | SpaceList: >>> from cognite.client.data_classes.data_modeling import SpaceApply >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> spaces = [SpaceApply(space="mySpace", description="My first space", name="My Space"), - ... SpaceApply(space="myOtherSpace", description="My second space", name="My Other Space")] + >>> spaces = [ + ... SpaceApply(space="mySpace", description="My first space", name="My Space"), + ... SpaceApply( + ... space="myOtherSpace", description="My second space", name="My Other Space" + ... ), + ... ] >>> res = client.data_modeling.spaces.apply(spaces) """ return run_sync(self.__async_client.data_modeling.spaces.apply(spaces=spaces)) diff --git a/cognite/client/_sync_api/data_modeling/views.py b/cognite/client/_sync_api/data_modeling/views.py index 7a698e2516..12e9269e6b 100644 --- a/cognite/client/_sync_api/data_modeling/views.py +++ b/cognite/client/_sync_api/data_modeling/views.py @@ -110,7 +110,7 @@ def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.data_modeling.views.retrieve(('mySpace', 'myView', 'v1')) + >>> res = client.data_modeling.views.retrieve(("mySpace", "myView", "v1")) """ return run_sync( self.__async_client.data_modeling.views.retrieve( @@ -133,7 +133,7 @@ def delete(self, ids: ViewIdentifier | Sequence[ViewIdentifier]) -> list[ViewId] >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.data_modeling.views.delete(('mySpace', 'myView', 'v1')) + >>> client.data_modeling.views.delete(("mySpace", "myView", "v1")) """ return run_sync(self.__async_client.data_modeling.views.delete(ids=ids)) @@ -175,7 +175,7 @@ def list( Iterate over chunks of views to reduce memory load: >>> for view_list in client.data_modeling.views(chunk_size=10): - ... view_list # do something with the views + ... view_list # do something with the views """ return run_sync( self.__async_client.data_modeling.views.list( @@ -208,7 +208,11 @@ def apply(self, view: ViewApply | Sequence[ViewApply]) -> View | ViewList: Create new views: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.data_modeling import ViewApply, MappedPropertyApply, ContainerId + >>> from cognite.client.data_classes.data_modeling import ( + ... ViewApply, + ... MappedPropertyApply, + ... ContainerId, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> views = [ @@ -221,8 +225,8 @@ def apply(self, view: ViewApply | Sequence[ViewApply]) -> View | ViewList: ... container=ContainerId("mySpace", "myContainer"), ... container_property_identifier="someProperty", ... ), - ... } - ... ) + ... }, + ... ) ... ] >>> res = client.data_modeling.views.apply(views) @@ -235,9 +239,11 @@ def apply(self, view: ViewApply | Sequence[ViewApply]) -> View | ViewList: ... MappedPropertyApply, ... MultiEdgeConnectionApply, ... ViewApply, - ... ViewId + ... ViewId, + ... ) + >>> work_order_for_asset = DirectRelationReference( + ... space="mySpace", external_id="work_order_for_asset" ... ) - >>> work_order_for_asset = DirectRelationReference(space="mySpace", external_id="work_order_for_asset") >>> work_order_view = ViewApply( ... space="mySpace", ... external_id="WorkOrder", @@ -254,7 +260,7 @@ def apply(self, view: ViewApply | Sequence[ViewApply]) -> View | ViewList: ... source=ViewId("mySpace", "Asset", "v1"), ... name="asset", ... ), - ... } + ... }, ... ) >>> asset_view = ViewApply( ... space="mySpace", @@ -273,7 +279,7 @@ def apply(self, view: ViewApply | Sequence[ViewApply]) -> View | ViewList: ... source=ViewId("mySpace", "WorkOrder", "v1"), ... name="work_orders", ... ), - ... } + ... }, ... ) >>> res = client.data_modeling.views.apply([work_order_view, asset_view]) """ diff --git a/cognite/client/_sync_api/data_sets.py b/cognite/client/_sync_api/data_sets.py index 89ba6556e5..ae8a88f2ff 100644 --- a/cognite/client/_sync_api/data_sets.py +++ b/cognite/client/_sync_api/data_sets.py @@ -175,7 +175,9 @@ def retrieve_multiple( Get data sets by external id: - >>> res = client.data_sets.retrieve_multiple(external_ids=["abc", "def"], ignore_unknown_ids=True) + >>> res = client.data_sets.retrieve_multiple( + ... external_ids=["abc", "def"], ignore_unknown_ids=True + ... ) """ return run_sync( self.__async_client.data_sets.retrieve_multiple( @@ -249,7 +251,9 @@ def update( Perform a partial update on a data set, updating the description and removing a field from metadata: >>> from cognite.client.data_classes import DataSetUpdate - >>> my_update = DataSetUpdate(id=1).description.set("New description").metadata.remove(["key"]) + >>> my_update = ( + ... DataSetUpdate(id=1).description.set("New description").metadata.remove(["key"]) + ... ) >>> res = client.data_sets.update(my_update) """ return run_sync(self.__async_client.data_sets.update(item=item, mode=mode)) @@ -294,7 +298,7 @@ def list( Iterate over chunks of data sets to reduce memory load: >>> for data_set_list in client.data_sets(chunk_size=2500): - ... data_set_list # do something with the list + ... data_set_list # do something with the list """ return run_sync( self.__async_client.data_sets.list( diff --git a/cognite/client/_sync_api/datapoints.py b/cognite/client/_sync_api/datapoints.py index fcc8ca7943..45d7534589 100644 --- a/cognite/client/_sync_api/datapoints.py +++ b/cognite/client/_sync_api/datapoints.py @@ -134,7 +134,7 @@ def __call__( >>> queries = [ ... DatapointsQuery(id=123), ... DatapointsQuery(external_id="foo"), - ... DatapointsQuery(instance_id=NodeId("my-space", "my-ts-xid")) + ... DatapointsQuery(instance_id=NodeId("my-space", "my-ts-xid")), ... ] >>> for chunk_lst in client.time_series.data(query, return_arrays=False): ... if chunk_lst.get(id=123) is None: @@ -468,11 +468,12 @@ def retrieve( (milliseconds after epoch). In the below example, we fetch them using their external ids: >>> dps_lst = client.time_series.data.retrieve( - ... external_id=["foo", "bar"], - ... start=1514764800000, - ... end=1546300800000, - ... aggregates=["max", "average"], - ... granularity="1d") + ... external_id=["foo", "bar"], + ... start=1514764800000, + ... end=1546300800000, + ... aggregates=["max", "average"], + ... granularity="1d", + ... ) In the two code examples above, we have a `dps` object (an instance of ``Datapoints``), and a `dps_lst` object (an instance of ``DatapointsList``). On `dps`, which in this case contains raw datapoints, you may access the underlying data directly by using the `.value` attribute. This works for @@ -509,7 +510,8 @@ def retrieve( ... ], ... external_id=DatapointsQuery(external_id="foo", aggregates="max"), ... start="5d-ago", - ... granularity="1h") + ... granularity="1h", + ... ) Certain aggregates are very useful when they follow the calendar, for example electricity consumption per day, week, month or year. You may request such calendar-based aggregates in a specific timezone to make them even more useful: daylight savings (DST) @@ -517,10 +519,8 @@ def retrieve( can be used independently. To get monthly local aggregates in Oslo, Norway you can do: >>> dps = client.time_series.data.retrieve( - ... id=123, - ... aggregates="sum", - ... granularity="1month", - ... timezone="Europe/Oslo") + ... id=123, aggregates="sum", granularity="1month", timezone="Europe/Oslo" + ... ) When requesting multiple time series, an easy way to get the datapoints of a specific one is to use the `.get` method on the returned ``DatapointsList`` object, then specify if you want `id` or `external_id`. Note: If you fetch a time series @@ -550,9 +550,12 @@ def retrieve( ... external_id=[ ... DatapointsQuery(external_id=sensor_xid, start=ev.start_time, end=ev.end_time) ... for ev in periods - ... ]) + ... ], + ... ) >>> ts_44 = dps_lst.get(id=44) # Single ``Datapoints`` object - >>> ts_lst = dps_lst.get(external_id=sensor_xid) # List of ``len(periods)`` ``Datapoints`` objects + >>> ts_lst = dps_lst.get( + ... external_id=sensor_xid + ... ) # List of ``len(periods)`` ``Datapoints`` objects The API has an endpoint to :py:meth:`~DatapointsAPI.retrieve_latest`, i.e. "before", but not "after". Luckily, we can emulate that behaviour easily. Let's say we have a very dense time series and do not want to fetch all of the available raw data (or fetch less precise @@ -561,10 +564,14 @@ def retrieve( >>> import itertools >>> month_starts = [ ... datetime(year, month, 1, tzinfo=utc) - ... for year, month in itertools.product(range(2000, 2011), range(1, 13))] + ... for year, month in itertools.product(range(2000, 2011), range(1, 13)) + ... ] >>> dps_lst = client.time_series.data.retrieve( - ... external_id=[DatapointsQuery(external_id="foo", start=start) for start in month_starts], - ... limit=1) + ... external_id=[ + ... DatapointsQuery(external_id="foo", start=start) for start in month_starts + ... ], + ... limit=1, + ... ) To get *all* historic and future datapoints for a time series, e.g. to do a backup, you may want to import the two integer constants: ``MIN_TIMESTAMP_MS`` and ``MAX_TIMESTAMP_MS``, to make sure you do not miss any. **Performance warning**: This pattern of @@ -572,28 +579,30 @@ def retrieve( >>> from cognite.client.utils import MIN_TIMESTAMP_MS, MAX_TIMESTAMP_MS >>> dps_backup = client.time_series.data.retrieve( - ... id=123, - ... start=MIN_TIMESTAMP_MS, - ... end=MAX_TIMESTAMP_MS + 1) # end is exclusive + ... id=123, start=MIN_TIMESTAMP_MS, end=MAX_TIMESTAMP_MS + 1 + ... ) # end is exclusive If you have a time series with 'unit_external_id' set, you can use the 'target_unit' parameter to convert the datapoints to the desired unit. In the example below, we are converting temperature readings from a sensor measured and stored in Celsius, to Fahrenheit (we're assuming that the time series has e.g. ``unit_external_id="temperature:deg_c"`` ): >>> client.time_series.data.retrieve( - ... id=42, start="2w-ago", target_unit="temperature:deg_f") + ... id=42, start="2w-ago", target_unit="temperature:deg_f" + ... ) Or alternatively, you can use the 'target_unit_system' parameter to convert the datapoints to the desired unit system: >>> client.time_series.data.retrieve( - ... id=42, start="2w-ago", target_unit_system="Imperial") + ... id=42, start="2w-ago", target_unit_system="Imperial" + ... ) To retrieve status codes for a time series, pass ``include_status=True``. This is only possible for raw datapoint queries. You would typically also pass ``ignore_bad_datapoints=False`` to not hide all the datapoints that are marked as uncertain or bad, which is the API's default behaviour. You may also use ``treat_uncertain_as_bad`` to control how uncertain values are interpreted. >>> dps = client.time_series.data.retrieve( - ... id=42, include_status=True, ignore_bad_datapoints=False) + ... id=42, include_status=True, ignore_bad_datapoints=False + ... ) >>> dps.status_code # list of integer codes, e.g.: [0, 1073741824, 2147483648] >>> dps.status_symbol # list of symbolic representations, e.g. [Good, Uncertain, Bad] @@ -815,7 +824,8 @@ def retrieve_arrays( ... id=42, ... start=datetime(2020, 1, 1, tzinfo=timezone.utc), ... aggregates=["min", "max"], - ... granularity="7d") + ... granularity="7d", + ... ) >>> weekly_range = dps.max - dps.min Get up-to 2 million raw datapoints for the last 48 hours for a noisy time series with external_id="ts-noisy", @@ -823,9 +833,8 @@ def retrieve_arrays( >>> import numpy as np >>> dps = client.time_series.data.retrieve_arrays( - ... external_id="ts-noisy", - ... start="2d-ago", - ... limit=2_000_000) + ... external_id="ts-noisy", start="2d-ago", limit=2_000_000 + ... ) >>> smooth = np.convolve(dps.value, np.ones(5) / 5) # doctest: +SKIP >>> smoother = np.convolve(dps.value, np.ones(20) / 20) # doctest: +SKIP @@ -834,10 +843,8 @@ def retrieve_arrays( >>> id_lst = [42, 43, 44] >>> dps_lst = client.time_series.data.retrieve_arrays( - ... id=id_lst, - ... start="2h-ago", - ... include_outside_points=True, - ... ignore_unknown_ids=True) + ... id=id_lst, start="2h-ago", include_outside_points=True, ignore_unknown_ids=True + ... ) >>> largest_gaps = [np.max(np.diff(dps.timestamp)) for dps in dps_lst] Get raw datapoints for a time series with external_id="bar" from the last 10 weeks, then convert to a ``pandas.Series`` @@ -946,10 +953,8 @@ def retrieve_dataframe( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> df = client.time_series.data.retrieve_dataframe( - ... external_id="foo", - ... start="2w-ago", - ... end="now", - ... limit=100) + ... external_id="foo", start="2w-ago", end="now", limit=100 + ... ) Get the pandas dataframe with a uniform index (fixed spacing between points) of 1 day, for two time series with individually specified aggregates, from 1990 through 2020: @@ -959,12 +964,15 @@ def retrieve_dataframe( >>> df = client.time_series.data.retrieve_dataframe( ... external_id=[ ... DatapointsQuery(external_id="foo", aggregates="discrete_variance"), - ... DatapointsQuery(external_id="bar", aggregates=["total_variation", "continuous_variance"]), + ... DatapointsQuery( + ... external_id="bar", aggregates=["total_variation", "continuous_variance"] + ... ), ... ], ... granularity="1d", ... start=datetime(1990, 1, 1, tzinfo=timezone.utc), ... end=datetime(2020, 12, 31, tzinfo=timezone.utc), - ... uniform_index=True) + ... uniform_index=True, + ... ) Get a pandas dataframe containing the 'average' aggregate for two time series using a monthly granularity, starting Jan 1, 1970 all the way up to present, without having the aggregate name in the columns: @@ -973,7 +981,8 @@ def retrieve_dataframe( ... external_id=["foo", "bar"], ... aggregates="average", ... granularity="1mo", - ... include_aggregate_name=False) + ... include_aggregate_name=False, + ... ) You may also use ``pandas.Timestamp`` to define start and end. Here we fetch using instance_id: @@ -981,7 +990,8 @@ def retrieve_dataframe( >>> df = client.time_series.data.retrieve_dataframe( ... instance_id=NodeId("my-space", "my-ts-xid"), ... start=pd.Timestamp("2023-01-01"), - ... end=pd.Timestamp("2023-02-01")) + ... end=pd.Timestamp("2023-02-01"), + ... ) """ return run_sync( self.__async_client.time_series.data.retrieve_dataframe( @@ -1231,8 +1241,8 @@ def retrieve_latest( >>> from cognite.client.data_classes.data_modeling import NodeId >>> res = client.time_series.data.retrieve_latest( - ... external_id=["foo", "bar"], - ... instance_id=NodeId("my-space", "my-ts-xid")) + ... external_id=["foo", "bar"], instance_id=NodeId("my-space", "my-ts-xid") + ... ) You can also get the latest datapoint before a specific time: @@ -1250,7 +1260,9 @@ def retrieve_latest( You may also pass an instance of LatestDatapointQuery: >>> from cognite.client.data_classes import LatestDatapointQuery - >>> res = client.time_series.data.retrieve_latest(id=LatestDatapointQuery(id=1, before=60_000)) + >>> res = client.time_series.data.retrieve_latest( + ... id=LatestDatapointQuery(id=1, before=60_000) + ... ) If you need the latest datapoint for multiple time series, simply give a list of ids. Note that we are using external ids here, but either will work: @@ -1268,16 +1280,23 @@ def retrieve_latest( >>> id_queries = [ ... 123, ... LatestDatapointQuery(id=456, before="1w-ago"), - ... LatestDatapointQuery(id=789, before=datetime(2018,1,1, tzinfo=timezone.utc)), - ... LatestDatapointQuery(id=987, target_unit="temperature:deg_f")] + ... LatestDatapointQuery(id=789, before=datetime(2018, 1, 1, tzinfo=timezone.utc)), + ... LatestDatapointQuery(id=987, target_unit="temperature:deg_f"), + ... ] >>> ext_id_queries = [ ... "foo", - ... LatestDatapointQuery(external_id="abc", before="3h-ago", target_unit_system="Imperial"), + ... LatestDatapointQuery( + ... external_id="abc", before="3h-ago", target_unit_system="Imperial" + ... ), ... LatestDatapointQuery(external_id="def", include_status=True), ... LatestDatapointQuery(external_id="ghi", treat_uncertain_as_bad=False), - ... LatestDatapointQuery(external_id="jkl", include_status=True, ignore_bad_datapoints=False)] + ... LatestDatapointQuery( + ... external_id="jkl", include_status=True, ignore_bad_datapoints=False + ... ), + ... ] >>> res = client.time_series.data.retrieve_latest( - ... id=id_queries, external_id=ext_id_queries) + ... id=id_queries, external_id=ext_id_queries + ... ) """ return run_sync( self.__async_client.time_series.data.retrieve_latest( @@ -1341,10 +1360,10 @@ def insert( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> datapoints = [ - ... (datetime(2018,1,1, tzinfo=timezone.utc), 1000), - ... (datetime(2018,1,2, tzinfo=timezone.utc), 2000, StatusCode.Good), - ... (datetime(2018,1,3, tzinfo=timezone.utc), 3000, StatusCode.Uncertain), - ... (datetime(2018,1,4, tzinfo=timezone.utc), None, StatusCode.Bad), + ... (datetime(2018, 1, 1, tzinfo=timezone.utc), 1000), + ... (datetime(2018, 1, 2, tzinfo=timezone.utc), 2000, StatusCode.Good), + ... (datetime(2018, 1, 3, tzinfo=timezone.utc), 3000, StatusCode.Uncertain), + ... (datetime(2018, 1, 4, tzinfo=timezone.utc), None, StatusCode.Bad), ... ] >>> client.time_series.data.insert(datapoints, id=1) @@ -1357,7 +1376,9 @@ def insert( ... (160000000000, 2000, 3145728), ... (170000000000, 2000, 2147483648), # Same as StatusCode.Bad ... ] - >>> client.time_series.data.insert(datapoints, instance_id=NodeId("my-space", "my-ts-xid")) + >>> client.time_series.data.insert( + ... datapoints, instance_id=NodeId("my-space", "my-ts-xid") + ... ) Or they can be a list of dictionaries: @@ -1367,7 +1388,11 @@ def insert( ... {"timestamp": 160000000000, "value": 2000}, ... {"timestamp": 170000000000, "value": 3000, "status": {"code": 0}}, ... {"timestamp": 180000000000, "value": 4000, "status": {"symbol": "Uncertain"}}, - ... {"timestamp": 190000000000, "value": math.nan, "status": {"code": StatusCode.Bad, "symbol": "Bad"}}, + ... { + ... "timestamp": 190000000000, + ... "value": math.nan, + ... "status": {"code": StatusCode.Bad, "symbol": "Bad"}, + ... }, ... ] >>> client.time_series.data.insert(datapoints, external_id="abcd") @@ -1432,35 +1457,61 @@ def insert_multiple( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> to_insert = [ - ... {"id": 1, "datapoints": [ - ... (datetime(2018,1,1, tzinfo=timezone.utc), 1000), - ... (datetime(2018,1,2, tzinfo=timezone.utc), 2000, StatusCode.Good)], + ... { + ... "id": 1, + ... "datapoints": [ + ... (datetime(2018, 1, 1, tzinfo=timezone.utc), 1000), + ... (datetime(2018, 1, 2, tzinfo=timezone.utc), 2000, StatusCode.Good), + ... ], ... }, - ... {"external_id": "foo", "datapoints": [ - ... (datetime(2018,1,3, tzinfo=timezone.utc), 3000), - ... (datetime(2018,1,4, tzinfo=timezone.utc), 4000, StatusCode.Uncertain)], + ... { + ... "external_id": "foo", + ... "datapoints": [ + ... (datetime(2018, 1, 3, tzinfo=timezone.utc), 3000), + ... (datetime(2018, 1, 4, tzinfo=timezone.utc), 4000, StatusCode.Uncertain), + ... ], + ... }, + ... { + ... "instance_id": NodeId("my-space", "my-ts-xid"), + ... "datapoints": [ + ... (datetime(2018, 1, 5, tzinfo=timezone.utc), 5000), + ... (datetime(2018, 1, 6, tzinfo=timezone.utc), None, StatusCode.Bad), + ... ], ... }, - ... {"instance_id": NodeId("my-space", "my-ts-xid"), "datapoints": [ - ... (datetime(2018,1,5, tzinfo=timezone.utc), 5000), - ... (datetime(2018,1,6, tzinfo=timezone.utc), None, StatusCode.Bad)], - ... } ... ] Passing datapoints using the dictionary format with timestamp given in milliseconds since epoch: >>> import math >>> to_insert.append( - ... {"external_id": "bar", "datapoints": [ - ... {"timestamp": 170000000, "value": 7000}, - ... {"timestamp": 180000000, "value": 8000, "status": {"symbol": "Uncertain"}}, - ... {"timestamp": 190000000, "value": None, "status": {"code": StatusCode.Bad}}, - ... {"timestamp": 200000000, "value": math.inf, "status": {"code": StatusCode.Bad, "symbol": "Bad"}}, - ... ]}) + ... { + ... "external_id": "bar", + ... "datapoints": [ + ... {"timestamp": 170000000, "value": 7000}, + ... { + ... "timestamp": 180000000, + ... "value": 8000, + ... "status": {"symbol": "Uncertain"}, + ... }, + ... { + ... "timestamp": 190000000, + ... "value": None, + ... "status": {"code": StatusCode.Bad}, + ... }, + ... { + ... "timestamp": 200000000, + ... "value": math.inf, + ... "status": {"code": StatusCode.Bad, "symbol": "Bad"}, + ... }, + ... ], + ... } + ... ) If the Datapoints or DatapointsArray are fetched with status codes, these will be automatically used in the insert: >>> data_to_clone = client.time_series.data.retrieve( - ... external_id="bar", include_status=True, ignore_bad_datapoints=False) + ... external_id="bar", include_status=True, ignore_bad_datapoints=False + ... ) >>> to_insert.append({"external_id": "bar-clone", "datapoints": data_to_clone}) >>> client.time_series.data.insert_multiple(to_insert) """ @@ -1517,8 +1568,10 @@ def delete_ranges(self, ranges: list[dict[str, Any]]) -> None: >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> ranges = [{"id": 1, "start": "2d-ago", "end": "now"}, - ... {"external_id": "abc", "start": "2d-ago", "end": "2d-ahead"}] + >>> ranges = [ + ... {"id": 1, "start": "2d-ago", "end": "now"}, + ... {"external_id": "abc", "start": "2d-ago", "end": "2d-ahead"}, + ... ] >>> client.time_series.data.delete_ranges(ranges) """ return run_sync(self.__async_client.time_series.data.delete_ranges(ranges=ranges)) @@ -1559,7 +1612,7 @@ def insert_dataframe(self, df: pd.DataFrame, dropna: bool = True) -> None: ... "foo": np.random.normal(0, 1, 100), ... node_id: np.random.normal(0, 1, 100), ... }, - ... index=pd.date_range(start="2018-01-01", periods=100, freq="1d") + ... index=pd.date_range(start="2018-01-01", periods=100, freq="1d"), ... ) >>> client.time_series.data.insert_dataframe(df) """ diff --git a/cognite/client/_sync_api/datapoints_subscriptions.py b/cognite/client/_sync_api/datapoints_subscriptions.py index 76900fa516..09d2103e76 100644 --- a/cognite/client/_sync_api/datapoints_subscriptions.py +++ b/cognite/client/_sync_api/datapoints_subscriptions.py @@ -79,7 +79,8 @@ def create(self, subscription: DataPointSubscriptionWrite) -> DatapointSubscript ... external_id="my_subscription", ... name="My subscription", ... partition_count=1, - ... time_series_ids=["myFistTimeSeries", "mySecondTimeSeries"]) + ... time_series_ids=["myFistTimeSeries", "mySecondTimeSeries"], + ... ) >>> created = client.time_series.subscriptions.create(sub) Create a subscription with explicit time series IDs given as Node IDs @@ -91,22 +92,30 @@ def create(self, subscription: DataPointSubscriptionWrite) -> DatapointSubscript ... external_id="my_subscription", ... name="My subscription with Data Model Ids", ... partition_count=1, - ... instance_ids=[NodeId("my_space", "myFistTimeSeries"), NodeId("my_space", "mySecondTimeSeries")]) + ... instance_ids=[ + ... NodeId("my_space", "myFistTimeSeries"), + ... NodeId("my_space", "mySecondTimeSeries"), + ... ], + ... ) >>> created = client.time_series.subscriptions.create(sub) Create a filter defined subscription for all numeric time series that are stepwise: >>> from cognite.client.data_classes import DataPointSubscriptionWrite >>> from cognite.client.data_classes import filters as flt - >>> from cognite.client.data_classes.datapoints_subscriptions import DatapointSubscriptionProperty + >>> from cognite.client.data_classes.datapoints_subscriptions import ( + ... DatapointSubscriptionProperty, + ... ) >>> is_numeric_stepwise = flt.And( ... flt.Equals(DatapointSubscriptionProperty.is_string, False), - ... flt.Equals(DatapointSubscriptionProperty.is_step, True)) + ... flt.Equals(DatapointSubscriptionProperty.is_step, True), + ... ) >>> sub = DataPointSubscriptionWrite( ... external_id="my_subscription", ... name="My subscription for numeric, stepwise time series", ... partition_count=1, - ... filter=is_numeric_stepwise) + ... filter=is_numeric_stepwise, + ... ) >>> created = client.time_series.subscriptions.create(sub) """ return run_sync(self.__async_client.time_series.subscriptions.create(subscription=subscription)) @@ -216,7 +225,9 @@ def update( Add a time series to a preexisting subscription: >>> from cognite.client.data_classes import DataPointSubscriptionUpdate - >>> update = DataPointSubscriptionUpdate("my_subscription").time_series_ids.add(["MyNewTimeSeriesExternalId"]) + >>> update = DataPointSubscriptionUpdate("my_subscription").time_series_ids.add( + ... ["MyNewTimeSeriesExternalId"] + ... ) >>> updated = client.time_series.subscriptions.update(update) """ return run_sync(self.__async_client.time_series.subscriptions.update(update=update, mode=mode)) @@ -279,7 +290,9 @@ def iterate_data( Iterate continuously over all changes to the subscription newer than 3 days: - >>> for batch in client.time_series.subscriptions.iterate_data("my_subscription", "3d-ago"): + >>> for batch in client.time_series.subscriptions.iterate_data( + ... "my_subscription", "3d-ago" + ... ): ... pass # do something """ yield from SyncIterator( diff --git a/cognite/client/_sync_api/diagrams.py b/cognite/client/_sync_api/diagrams.py index 2ce3acf2b8..525ccd1af9 100644 --- a/cognite/client/_sync_api/diagrams.py +++ b/cognite/client/_sync_api/diagrams.py @@ -115,8 +115,9 @@ def detect( >>> # async_client = AsyncCogniteClient() # another option >>> detect_job = client.diagrams.detect( ... entities=[ - ... {"userDefinedField": "21PT1017","ignoredField": "AA11"}, - ... {"userDefinedField": "21PT1018"}], + ... {"userDefinedField": "21PT1017", "ignoredField": "AA11"}, + ... {"userDefinedField": "21PT1018"}, + ... ], ... search_field="userDefinedField", ... partial_match=True, ... min_tokens=2, @@ -124,8 +125,9 @@ def detect( ... file_external_ids=["Test1"], ... file_references=[ ... FileReference(id=20, first_page=1, last_page=10), - ... FileReference(external_id="ext_20", first_page=11, last_page=20) - ... ]) + ... FileReference(external_id="ext_20", first_page=11, last_page=20), + ... ], + ... ) >>> result = detect_job.get_result() >>> print(result) @@ -161,13 +163,16 @@ def detect( To use beta configuration options you can use a dictionary or `DiagramDetectConfig` object for convenience: - >>> from cognite.client.data_classes.contextualization import ConnectionFlags, DiagramDetectConfig + >>> from cognite.client.data_classes.contextualization import ( + ... ConnectionFlags, + ... DiagramDetectConfig, + ... ) >>> config = DiagramDetectConfig( ... remove_leading_zeros=True, ... connection_flags=ConnectionFlags( ... no_text_inbetween=True, ... natural_reading_order=True, - ... ) + ... ), ... ) >>> job = client.diagrams.detect(entities=[{"name": "A1"}], file_id=123, config=config) diff --git a/cognite/client/_sync_api/document_preview.py b/cognite/client/_sync_api/document_preview.py index 793bbf0707..3294dc2f9e 100644 --- a/cognite/client/_sync_api/document_preview.py +++ b/cognite/client/_sync_api/document_preview.py @@ -45,7 +45,9 @@ def download_page_as_png_bytes(self, id: int, page_number: int = 1) -> bytes: Download an image preview and display using IPython.display.Image (for example in a Jupyter Notebook): >>> from IPython.display import Image - >>> binary_png = client.documents.previews.download_page_as_png_bytes(id=123, page_number=5) + >>> binary_png = client.documents.previews.download_page_as_png_bytes( + ... id=123, page_number=5 + ... ) >>> Image(binary_png) """ return run_sync( diff --git a/cognite/client/_sync_api/documents.py b/cognite/client/_sync_api/documents.py index 18b72e0946..43c812f2a4 100644 --- a/cognite/client/_sync_api/documents.py +++ b/cognite/client/_sync_api/documents.py @@ -115,7 +115,7 @@ def aggregate_count(self, query: str | None = None, filter: Filter | dict[str, A >>> client.documents.aggregate_count( ... filter=filters.InAssetSubtree( ... property=DocumentProperty.asset_external_ids, - ... values=['Plant_1', 'Plant_2'], + ... values=["Plant_1", "Plant_2"], ... ) ... ) """ @@ -155,7 +155,9 @@ def aggregate_cardinality_values( >>> from cognite.client.data_classes import filters >>> from cognite.client.data_classes.documents import DocumentProperty >>> is_plain_text = filters.Equals(DocumentProperty.mime_type, "text/plain") - >>> plain_text_author_count = client.documents.aggregate_cardinality_values(DocumentProperty.author, filter=is_plain_text) + >>> plain_text_author_count = client.documents.aggregate_cardinality_values( + ... DocumentProperty.author, filter=is_plain_text + ... ) Count the number of types of documents in your CDF project but exclude documents that start with "text": @@ -163,7 +165,9 @@ def aggregate_cardinality_values( >>> from cognite.client.data_classes import aggregations >>> agg = aggregations >>> is_not_text = agg.Not(agg.Prefix("text")) - >>> type_count_excluded_text = client.documents.aggregate_cardinality_values(DocumentProperty.type, aggregate_filter=is_not_text) + >>> type_count_excluded_text = client.documents.aggregate_cardinality_values( + ... DocumentProperty.type, aggregate_filter=is_not_text + ... ) """ return run_sync( self.__async_client.documents.aggregate_cardinality_values( @@ -242,7 +246,9 @@ def aggregate_unique_values( >>> from cognite.client.data_classes import filters >>> from cognite.client.data_classes.documents import DocumentProperty >>> is_abc = filters.Prefix(DocumentProperty.external_id, "abc") - >>> result = client.documents.aggregate_unique_values(DocumentProperty.language, filter=is_abc) + >>> result = client.documents.aggregate_unique_values( + ... DocumentProperty.language, filter=is_abc + ... ) >>> unique_languages = result.unique Get the unique mime types with count of documents, but exclude mime types that start with text: @@ -251,7 +257,9 @@ def aggregate_unique_values( >>> from cognite.client.data_classes import aggregations >>> agg = aggregations >>> is_not_text = agg.Not(agg.Prefix("text")) - >>> result = client.documents.aggregate_unique_values(DocumentProperty.mime_type, aggregate_filter=is_not_text) + >>> result = client.documents.aggregate_unique_values( + ... DocumentProperty.mime_type, aggregate_filter=is_not_text + ... ) >>> unique_mime_types = result.unique """ return run_sync( @@ -447,11 +455,15 @@ def search( >>> from cognite.client.data_classes.documents import DocumentProperty >>> from cognite.client.utils import timestamp_to_ms >>> is_plain_text = filters.Equals(DocumentProperty.mime_type, "text/plain") - >>> last_week = filters.Range(DocumentProperty.created_time, - ... gt=timestamp_to_ms(datetime.now() - timedelta(days=7))) - >>> documents = client.documents.search('"CPLEX Error 1217: No Solution exists."', + >>> last_week = filters.Range( + ... DocumentProperty.created_time, + ... gt=timestamp_to_ms(datetime.now() - timedelta(days=7)), + ... ) + >>> documents = client.documents.search( + ... '"CPLEX Error 1217: No Solution exists."', ... highlight=True, - ... filter=filters.And(is_plain_text, last_week)) + ... filter=filters.And(is_plain_text, last_week), + ... ) """ return run_sync( self.__async_client.documents.search( # type: ignore [call-overload] diff --git a/cognite/client/_sync_api/entity_matching.py b/cognite/client/_sync_api/entity_matching.py index 86eb53d55e..4cb7a99327 100644 --- a/cognite/client/_sync_api/entity_matching.py +++ b/cognite/client/_sync_api/entity_matching.py @@ -67,7 +67,7 @@ def retrieve_multiple( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> retrieved_models = client.entity_matching.retrieve_multiple([1,2,3]) + >>> retrieved_models = client.entity_matching.retrieve_multiple([1, 2, 3]) """ return run_sync(self.__async_client.entity_matching.retrieve_multiple(ids=ids, external_ids=external_ids)) @@ -204,14 +204,16 @@ def fit( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> sources = [{'id': 101, 'name': 'ChildAsset1', 'description': 'Child of ParentAsset1'}] - >>> targets = [{'id': 1, 'name': 'ParentAsset1', 'description': 'Parent to ChildAsset1'}] + >>> sources = [ + ... {"id": 101, "name": "ChildAsset1", "description": "Child of ParentAsset1"} + ... ] + >>> targets = [{"id": 1, "name": "ParentAsset1", "description": "Parent to ChildAsset1"}] >>> true_matches = [(1, 101)] >>> model = client.entity_matching.fit( ... sources=sources, ... targets=targets, ... true_matches=true_matches, - ... description="AssetMatchingJob1" + ... description="AssetMatchingJob1", ... ) """ return run_sync( @@ -263,15 +265,11 @@ def predict( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> sources = {'id': 101, 'name': 'ChildAsset1', 'description': 'Child of ParentAsset1'} - >>> targets = {'id': 1, 'name': 'ParentAsset1', 'description': 'Parent to ChildAsset1'} + >>> sources = {"id": 101, "name": "ChildAsset1", "description": "Child of ParentAsset1"} + >>> targets = {"id": 1, "name": "ParentAsset1", "description": "Parent to ChildAsset1"} >>> true_matches = [(1, 101)] >>> model = client.entity_matching.predict( - ... sources = sources, - ... targets = targets, - ... num_matches = 1, - ... score_threshold = 0.6, - ... id=1 + ... sources=sources, targets=targets, num_matches=1, score_threshold=0.6, id=1 ... ) """ return run_sync( @@ -309,8 +307,10 @@ def refit( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> sources = [{'id': 101, 'name': 'ChildAsset1', 'description': 'Child of ParentAsset1'}] - >>> targets = [{'id': 1, 'name': 'ParentAsset1', 'description': 'Parent to ChildAsset1'}] + >>> sources = [ + ... {"id": 101, "name": "ChildAsset1", "description": "Child of ParentAsset1"} + ... ] + >>> targets = [{"id": 1, "name": "ParentAsset1", "description": "Parent to ChildAsset1"}] >>> true_matches = [(1, 101)] >>> model = client.entity_matching.refit(true_matches=true_matches, id=1) """ diff --git a/cognite/client/_sync_api/events.py b/cognite/client/_sync_api/events.py index 14d9ea745d..d700cb52a1 100644 --- a/cognite/client/_sync_api/events.py +++ b/cognite/client/_sync_api/events.py @@ -261,8 +261,12 @@ def aggregate_unique_values( >>> from cognite.client.data_classes.events import EventProperty >>> from cognite.client.utils import timestamp_to_ms >>> from datetime import datetime - >>> is_after_2020 = filters.Range(EventProperty.start_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.events.aggregate_unique_values(EventProperty.type, advanced_filter=is_after_2020) + >>> is_after_2020 = filters.Range( + ... EventProperty.start_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.events.aggregate_unique_values( + ... EventProperty.type, advanced_filter=is_after_2020 + ... ) >>> print(result.unique) Get the unique types of events after 2020-01-01 in your CDF project, but exclude all types that start with @@ -272,8 +276,12 @@ def aggregate_unique_values( >>> from cognite.client.data_classes import aggregations >>> agg = aggregations >>> not_planned = agg.Not(agg.Prefix("planned")) - >>> is_after_2020 = filters.Range(EventProperty.start_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.events.aggregate_unique_values(EventProperty.type, advanced_filter=is_after_2020, aggregate_filter=not_planned) + >>> is_after_2020 = filters.Range( + ... EventProperty.start_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.events.aggregate_unique_values( + ... EventProperty.type, advanced_filter=is_after_2020, aggregate_filter=not_planned + ... ) >>> print(result.unique) """ return run_sync( @@ -355,7 +363,9 @@ def aggregate_cardinality_values( >>> from cognite.client.data_classes import filters >>> from cognite.client.data_classes.events import EventProperty >>> is_asset = filters.ContainsAny(EventProperty.asset_ids, 123) - >>> plain_text_author_count = client.events.aggregate_cardinality_values(EventProperty.type, advanced_filter=is_asset) + >>> plain_text_author_count = client.events.aggregate_cardinality_values( + ... EventProperty.type, advanced_filter=is_asset + ... ) """ return run_sync( self.__async_client.events.aggregate_cardinality_values( @@ -485,7 +495,7 @@ def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.events.delete(id=[1,2,3], external_id="3") + >>> client.events.delete(id=[1, 2, 3], external_id="3") """ return run_sync( self.__async_client.events.delete(id=id, external_id=external_id, ignore_unknown_ids=ignore_unknown_ids) @@ -534,7 +544,11 @@ def update( Perform a partial update on a event, updating the description and adding a new field to metadata: >>> from cognite.client.data_classes import EventUpdate - >>> my_update = EventUpdate(id=1).description.set("New description").metadata.add({"key": "value"}) + >>> my_update = ( + ... EventUpdate(id=1) + ... .description.set("New description") + ... .metadata.add({"key": "value"}) + ... ) >>> res = client.events.update(my_update) """ return run_sync(self.__async_client.events.update(item=item, mode=mode)) @@ -681,7 +695,7 @@ def list( Iterate over chunks of events to reduce memory load: >>> for event_list in client.events(chunk_size=2500): - ... event_list # do something with the events + ... event_list # do something with the events Using advanced filter, find all events that have a metadata key 'timezone' starting with 'Europe', and sort by external id ascending: @@ -700,17 +714,19 @@ def list( >>> from cognite.client.data_classes.events import EventProperty, SortableEventProperty >>> in_timezone = filters.Prefix(EventProperty.metadata_key("timezone"), "Europe") >>> res = client.events.list( - ... advanced_filter=in_timezone, - ... sort=(SortableEventProperty.external_id, "asc")) + ... advanced_filter=in_timezone, sort=(SortableEventProperty.external_id, "asc") + ... ) Combine filter and advanced filter: >>> from cognite.client.data_classes import filters >>> not_instrument_lvl5 = filters.And( - ... filters.ContainsAny("labels", ["Level5"]), - ... filters.Not(filters.ContainsAny("labels", ["Instrument"])) + ... filters.ContainsAny("labels", ["Level5"]), + ... filters.Not(filters.ContainsAny("labels", ["Instrument"])), + ... ) + >>> res = client.events.list( + ... asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5 ... ) - >>> res = client.events.list(asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5) """ return run_sync( self.__async_client.events.list( diff --git a/cognite/client/_sync_api/extractionpipelines/__init__.py b/cognite/client/_sync_api/extractionpipelines/__init__.py index 736e92ed26..0e9c523a31 100644 --- a/cognite/client/_sync_api/extractionpipelines/__init__.py +++ b/cognite/client/_sync_api/extractionpipelines/__init__.py @@ -107,7 +107,9 @@ def retrieve_multiple( Get assets by external id: - >>> res = client.extraction_pipelines.retrieve_multiple(external_ids=["abc", "def"], ignore_unknown_ids=True) + >>> res = client.extraction_pipelines.retrieve_multiple( + ... external_ids=["abc", "def"], ignore_unknown_ids=True + ... ) """ return run_sync( self.__async_client.extraction_pipelines.retrieve_multiple( @@ -192,7 +194,7 @@ def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.extraction_pipelines.delete(id=[1,2,3], external_id="3") + >>> client.extraction_pipelines.delete(id=[1, 2, 3], external_id="3") """ return run_sync(self.__async_client.extraction_pipelines.delete(id=id, external_id=external_id)) diff --git a/cognite/client/_sync_api/extractionpipelines/configs.py b/cognite/client/_sync_api/extractionpipelines/configs.py index f59b02ebee..749182560b 100644 --- a/cognite/client/_sync_api/extractionpipelines/configs.py +++ b/cognite/client/_sync_api/extractionpipelines/configs.py @@ -89,7 +89,9 @@ def create(self, config: ExtractionPipelineConfig | ExtractionPipelineConfigWrit >>> from cognite.client import CogniteClient >>> from cognite.client.data_classes import ExtractionPipelineConfigWrite >>> client = CogniteClient() - >>> res = client.extraction_pipelines.config.create(ExtractionPipelineConfigWrite(external_id="extId", config="my config contents")) + >>> res = client.extraction_pipelines.config.create( + ... ExtractionPipelineConfigWrite(external_id="extId", config="my config contents") + ... ) """ return run_sync(self.__async_client.extraction_pipelines.config.create(config=config)) diff --git a/cognite/client/_sync_api/extractionpipelines/runs.py b/cognite/client/_sync_api/extractionpipelines/runs.py index e4003986ff..9f0ecdfb7e 100644 --- a/cognite/client/_sync_api/extractionpipelines/runs.py +++ b/cognite/client/_sync_api/extractionpipelines/runs.py @@ -70,12 +70,16 @@ def list( Filter extraction pipeline runs on a given status: - >>> runs_list = client.extraction_pipelines.runs.list(external_id="test ext id", statuses=["seen"], limit=5) + >>> runs_list = client.extraction_pipelines.runs.list( + ... external_id="test ext id", statuses=["seen"], limit=5 + ... ) Get all failed pipeline runs in the last 24 hours for pipeline 'extId': >>> from cognite.client.data_classes import ExtractionPipelineRun - >>> res = client.extraction_pipelines.runs.list(external_id="extId", statuses="failure", created_time="24h-ago") + >>> res = client.extraction_pipelines.runs.list( + ... external_id="extId", statuses="failure", created_time="24h-ago" + ... ) """ return run_sync( self.__async_client.extraction_pipelines.runs.list( @@ -121,6 +125,7 @@ def create( >>> from cognite.client.data_classes import ExtractionPipelineRunWrite >>> client = CogniteClient() >>> res = client.extraction_pipelines.runs.create( - ... ExtractionPipelineRunWrite(status="success", extpipe_external_id="extId")) + ... ExtractionPipelineRunWrite(status="success", extpipe_external_id="extId") + ... ) """ return run_sync(self.__async_client.extraction_pipelines.runs.create(run=run)) diff --git a/cognite/client/_sync_api/files.py b/cognite/client/_sync_api/files.py index 743c6ba7d4..6da9ad130f 100644 --- a/cognite/client/_sync_api/files.py +++ b/cognite/client/_sync_api/files.py @@ -311,7 +311,7 @@ def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.files.delete(id=[1,2,3], external_id="3") + >>> client.files.delete(id=[1, 2, 3], external_id="3") """ return run_sync( self.__async_client.files.delete(id=id, external_id=external_id, ignore_unknown_ids=ignore_unknown_ids) @@ -364,7 +364,9 @@ def update( Perform a partial update on file metadata, updating the source and adding a new field to metadata: >>> from cognite.client.data_classes import FileMetadataUpdate - >>> my_update = FileMetadataUpdate(id=1).source.set("new source").metadata.add({"key": "value"}) + >>> my_update = ( + ... FileMetadataUpdate(id=1).source.set("new source").metadata.add({"key": "value"}) + ... ) >>> res = client.files.update(my_update) Attach labels to a files: @@ -411,7 +413,9 @@ def search( Search for an asset with an attached label: >>> my_label_filter = LabelFilter(contains_all=["WELL LOG"]) - >>> res = client.assets.search(name="xyz",filter=FileMetadataFilter(labels=my_label_filter)) + >>> res = client.assets.search( + ... name="xyz", filter=FileMetadataFilter(labels=my_label_filter) + ... ) """ return run_sync(self.__async_client.files.search(name=name, filter=filter, limit=limit)) @@ -503,13 +507,17 @@ def upload( Upload a file with a label: >>> from cognite.client.data_classes import Label - >>> res = client.files.upload(my_file, name="my_file", labels=[Label(external_id="WELL LOG")]) + >>> res = client.files.upload( + ... my_file, name="my_file", labels=[Label(external_id="WELL LOG")] + ... ) Upload a file with a geo_location: >>> from cognite.client.data_classes import GeoLocation, Geometry >>> geometry = Geometry(type="LineString", coordinates=[[30, 10], [10, 30], [40, 40]]) - >>> res = client.files.upload(my_file, geo_location=GeoLocation(type="Feature", geometry=geometry)) + >>> res = client.files.upload( + ... my_file, geo_location=GeoLocation(type="Feature", geometry=geometry) + ... ) """ return run_sync( self.__async_client.files.upload( @@ -555,14 +563,14 @@ def upload_content_bytes( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.files.upload_content_bytes( - ... b"some content", external_id="my_file_xid") + >>> res = client.files.upload_content_bytes(b"some content", external_id="my_file_xid") ...or by using instance_id: >>> from cognite.client.data_classes.data_modeling import NodeId >>> res = client.files.upload_content_bytes( - ... b"some content", instance_id=NodeId("my-space", "my_file_xid")) + ... b"some content", instance_id=NodeId("my-space", "my_file_xid") + ... ) """ return run_sync( self.__async_client.files.upload_content_bytes( @@ -622,7 +630,7 @@ def upload_bytes( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.files.upload_bytes(b"some content", name="my_file", asset_ids=[1,2,3]) + >>> res = client.files.upload_bytes(b"some content", name="my_file", asset_ids=[1, 2, 3]) """ return run_sync( self.__async_client.files.upload_bytes( @@ -754,7 +762,9 @@ def multipart_upload_content_session( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> with client.files.multipart_upload_content_session(external_id="external-id", parts=2) as session: + >>> with client.files.multipart_upload_content_session( + ... external_id="external-id", parts=2 + ... ) as session: ... # Note that the minimum chunk size is 5 MiB. ... session.upload_part(0, "hello" * 1_200_000) ... session.upload_part(1, " world") @@ -829,11 +839,13 @@ def download( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.files.download(directory="my_directory", id=[1,2,3], external_id=["abc", "def"]) + >>> client.files.download( + ... directory="my_directory", id=[1, 2, 3], external_id=["abc", "def"] + ... ) Download files by id to the current directory: - >>> client.files.download(directory=".", id=[1,2,3]) + >>> client.files.download(directory=".", id=[1, 2, 3]) """ return run_sync( self.__async_client.files.download( @@ -971,7 +983,7 @@ def list( Iterate over chunks of files metadata to reduce memory load: >>> for file_list in client.files(chunk_size=2500): - ... file_list # do something with the files + ... file_list # do something with the files Filter files based on labels: @@ -982,7 +994,9 @@ def list( Filter files based on geoLocation: >>> from cognite.client.data_classes import GeoLocationFilter, GeometryFilter - >>> my_geo_location_filter = GeoLocationFilter(relation="intersects", shape=GeometryFilter(type="Point", coordinates=[35,10])) + >>> my_geo_location_filter = GeoLocationFilter( + ... relation="intersects", shape=GeometryFilter(type="Point", coordinates=[35, 10]) + ... ) >>> file_list = client.files.list(geo_location=my_geo_location_filter) """ return run_sync( diff --git a/cognite/client/_sync_api/functions/__init__.py b/cognite/client/_sync_api/functions/__init__.py index 686e1f9346..8176cba809 100644 --- a/cognite/client/_sync_api/functions/__init__.py +++ b/cognite/client/_sync_api/functions/__init__.py @@ -186,14 +186,14 @@ def create( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> function = client.functions.create( - ... name="myfunction", - ... folder="path/to/code", - ... function_path="path/to/function.py") + ... name="myfunction", folder="path/to/code", function_path="path/to/function.py" + ... ) Create function with file_id from already uploaded source code: >>> function = client.functions.create( - ... name="myfunction", file_id=123, function_path="path/to/function.py") + ... name="myfunction", file_id=123, function_path="path/to/function.py" + ... ) Create function with predefined function object named `handle`: diff --git a/cognite/client/_sync_api/functions/schedules.py b/cognite/client/_sync_api/functions/schedules.py index e007e43c94..dc5bfcc309 100644 --- a/cognite/client/_sync_api/functions/schedules.py +++ b/cognite/client/_sync_api/functions/schedules.py @@ -222,7 +222,9 @@ def create( ... name="My schedule", ... function_id=123, ... cron_expression="*/5 * * * *", - ... client_credentials=ClientCredentials("my-client-id", os.environ["MY_CLIENT_SECRET"]), + ... client_credentials=ClientCredentials( + ... "my-client-id", os.environ["MY_CLIENT_SECRET"] + ... ), ... description="This schedule does magic stuff.", ... data={"magic": "stuff"}, ... ) @@ -249,7 +251,7 @@ def create( ... function_id=456, ... cron_expression="*/5 * * * *", ... description="A schedule just used for some temporary testing.", - ... nonce=session.nonce + ... nonce=session.nonce, ... ), ... ) """ @@ -279,7 +281,7 @@ def delete(self, id: int) -> None: >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.functions.schedules.delete(id = 123) + >>> client.functions.schedules.delete(id=123) """ return run_sync(self.__async_client.functions.schedules.delete(id=id)) diff --git a/cognite/client/_sync_api/geospatial.py b/cognite/client/_sync_api/geospatial.py index 89c97616e1..2a402b12e3 100644 --- a/cognite/client/_sync_api/geospatial.py +++ b/cognite/client/_sync_api/geospatial.py @@ -121,7 +121,7 @@ def list_feature_types(self) -> FeatureTypeList: >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> for feature_type in client.geospatial.list_feature_types(): - ... feature_type # do something with the feature type definition + ... feature_type # do something with the feature type definition """ return run_sync(self.__async_client.geospatial.list_feature_types()) @@ -173,26 +173,29 @@ def patch_feature_types(self, patch: FeatureTypePatch | Sequence[FeatureTypePatc >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> res = client.geospatial.patch_feature_types( - ... patch=FeatureTypePatch( - ... external_id="wells", - ... property_patches=Patches(add={"altitude": {"type": "DOUBLE"}}), - ... search_spec_patches=Patches( - ... add={ - ... "altitude_idx": {"properties": ["altitude"]}, - ... "composite_idx": {"properties": ["location", "altitude"]} - ... } - ... ) - ... ) + ... patch=FeatureTypePatch( + ... external_id="wells", + ... property_patches=Patches(add={"altitude": {"type": "DOUBLE"}}), + ... search_spec_patches=Patches( + ... add={ + ... "altitude_idx": {"properties": ["altitude"]}, + ... "composite_idx": {"properties": ["location", "altitude"]}, + ... } + ... ), + ... ) ... ) Add an additional index to an existing property >>> from cognite.client.data_classes.geospatial import Patches >>> res = client.geospatial.patch_feature_types( - ... patch=FeatureTypePatch( + ... patch=FeatureTypePatch( ... external_id="wells", - ... search_spec_patches=Patches(add={"location_idx": {"properties": ["location"]}}) - ... )) + ... search_spec_patches=Patches( + ... add={"location_idx": {"properties": ["location"]}} + ... ), + ... ) + ... ) """ return run_sync(self.__async_client.geospatial.patch_feature_types(patch=patch)) @@ -247,18 +250,16 @@ def create_features( ... external_id="my_feature_type", ... properties={ ... "location": {"type": "POINT", "srid": 4326}, - ... "temperature": {"type": "DOUBLE"} - ... } + ... "temperature": {"type": "DOUBLE"}, + ... }, ... ) ... ] >>> res = client.geospatial.create_feature_types(feature_types) >>> res = client.geospatial.create_features( ... feature_type_external_id="my_feature_type", ... feature=FeatureWrite( - ... external_id="my_feature", - ... location={"wkt": "POINT(1 1)"}, - ... temperature=12.4 - ... ) + ... external_id="my_feature", location={"wkt": "POINT(1 1)"}, temperature=12.4 + ... ), ... ) """ return run_sync( @@ -289,8 +290,7 @@ def delete_features( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> client.geospatial.delete_features( - ... feature_type_external_id="my_feature_type", - ... external_id=my_feature + ... feature_type_external_id="my_feature_type", external_id=my_feature ... ) """ return run_sync( @@ -332,8 +332,7 @@ def retrieve_features( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> client.geospatial.retrieve_features( - ... feature_type_external_id="my_feature_type", - ... external_id="my_feature" + ... feature_type_external_id="my_feature_type", external_id="my_feature" ... ) """ return run_sync( @@ -389,11 +388,11 @@ def update_features( >>> # async_client = AsyncCogniteClient() # another option >>> my_feature = client.geospatial.create_features( ... feature_type_external_id="my_feature_type", - ... feature=Feature(external_id="my_feature", temperature=12.4) + ... feature=Feature(external_id="my_feature", temperature=12.4), ... ) >>> my_updated_feature = client.geospatial.update_features( ... feature_type_external_id="my_feature_type", - ... feature=Feature(external_id="my_feature", temperature=6.237) + ... feature=Feature(external_id="my_feature", temperature=6.237), ... ) """ return run_sync( @@ -442,14 +441,12 @@ def list_features( >>> my_feature = client.geospatial.create_features( ... feature_type_external_id=my_feature_type, ... feature=Feature( - ... external_id="my_feature", - ... temperature=12.4, - ... location={"wkt": "POINT(0 1)"} - ... ) + ... external_id="my_feature", temperature=12.4, location={"wkt": "POINT(0 1)"} + ... ), ... ) >>> res = client.geospatial.list_features( ... feature_type_external_id="my_feature_type", - ... filter={"range": {"property": "temperature", "gt": 12.0}} + ... filter={"range": {"property": "temperature", "gt": 12.0}}, ... ) >>> for f in res: ... # do something with the features @@ -459,17 +456,19 @@ def list_features( >>> res = client.geospatial.list_features( ... feature_type_external_id=my_feature_type, ... filter={}, - ... properties={"temperature": {}, "pressure": {}} + ... properties={"temperature": {}, "pressure": {}}, ... ) Search for features with spatial filters: >>> res = client.geospatial.list_features( ... feature_type_external_id=my_feature_type, - ... filter={"stWithin": { - ... "property": "location", - ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"} - ... }} + ... filter={ + ... "stWithin": { + ... "property": "location", + ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"}, + ... } + ... }, ... ) """ return run_sync( @@ -525,14 +524,12 @@ def search_features( >>> my_feature = client.geospatial.create_features( ... feature_type_external_id=my_feature_type, ... feature=Feature( - ... external_id="my_feature", - ... temperature=12.4, - ... location={"wkt": "POINT(0 1)"} - ... ) + ... external_id="my_feature", temperature=12.4, location={"wkt": "POINT(0 1)"} + ... ), ... ) >>> res = client.geospatial.search_features( ... feature_type_external_id="my_feature_type", - ... filter={"range": {"property": "temperature", "gt": 12.0}} + ... filter={"range": {"property": "temperature", "gt": 12.0}}, ... ) >>> for f in res: ... # do something with the features @@ -542,7 +539,7 @@ def search_features( >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, ... filter={}, - ... properties={"temperature": {}, "pressure": {}} + ... properties={"temperature": {}, "pressure": {}}, ... ) Search for features and do CRS conversion on an output property: @@ -550,7 +547,7 @@ def search_features( >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, ... filter={}, - ... properties={"location": {"srid": 3995}} + ... properties={"location": {"srid": 3995}}, ... ) Search for features and order results: @@ -558,43 +555,51 @@ def search_features( >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, ... filter={}, - ... order_by=[ - ... OrderSpec("temperature", "ASC"), - ... OrderSpec("pressure", "DESC")] + ... order_by=[OrderSpec("temperature", "ASC"), OrderSpec("pressure", "DESC")], ... ) Search for features with spatial filters: >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, - ... filter={"stWithin": { - ... "property": "location", - ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"} - ... }} + ... filter={ + ... "stWithin": { + ... "property": "location", + ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"}, + ... } + ... }, ... ) Combining multiple filters: >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, - ... filter={"and": [ - ... {"range": {"property": "temperature", "gt": 12.0}}, - ... {"stWithin": { - ... "property": "location", - ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"} - ... }} - ... ]} + ... filter={ + ... "and": [ + ... {"range": {"property": "temperature", "gt": 12.0}}, + ... { + ... "stWithin": { + ... "property": "location", + ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"}, + ... } + ... }, + ... ] + ... }, ... ) >>> res = client.geospatial.search_features( ... feature_type_external_id=my_feature_type, - ... filter={"or": [ - ... {"range": {"property": "temperature", "gt": 12.0}}, - ... {"stWithin": { - ... "property": "location", - ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"} - ... }} - ... ]} + ... filter={ + ... "or": [ + ... {"range": {"property": "temperature", "gt": 12.0}}, + ... { + ... "stWithin": { + ... "property": "location", + ... "value": {"wkt": "POLYGON((0 0, 0 1, 1 1, 0 0))"}, + ... } + ... }, + ... ] + ... }, ... ) """ return run_sync( @@ -644,11 +649,11 @@ def stream_features( >>> # async_client = AsyncCogniteClient() # another option >>> my_feature = client.geospatial.create_features( ... feature_type_external_id="my_feature_type", - ... feature=Feature(external_id="my_feature", temperature=12.4) + ... feature=Feature(external_id="my_feature", temperature=12.4), ... ) >>> features = client.geospatial.stream_features( ... feature_type_external_id="my_feature_type", - ... filter={"range": {"property": "temperature", "gt": 12.0}} + ... filter={"range": {"property": "temperature", "gt": 12.0}}, ... ) >>> for f in features: ... # do something with the features @@ -658,7 +663,7 @@ def stream_features( >>> features = client.geospatial.stream_features( ... feature_type_external_id="my_feature_type", ... filter={}, - ... properties={"temperature": {}, "pressure": {}} + ... properties={"temperature": {}, "pressure": {}}, ... ) >>> for f in features: ... # do something with the features @@ -704,16 +709,17 @@ def aggregate_features( >>> # async_client = AsyncCogniteClient() # another option >>> my_feature = client.geospatial.create_features( ... feature_type_external_id="my_feature_type", - ... feature=Feature(external_id="my_feature", temperature=12.4) + ... feature=Feature(external_id="my_feature", temperature=12.4), ... ) >>> res = client.geospatial.aggregate_features( ... feature_type_external_id="my_feature_type", ... filter={"range": {"property": "temperature", "gt": 12.0}}, ... group_by=["category"], ... order_by=[OrderSpec("category", "ASC")], - ... output={"min_temperature": {"min": {"property": "temperature"}}, - ... "max_volume": {"max": {"property": "volume"}} - ... } + ... output={ + ... "min_temperature": {"min": {"property": "temperature"}}, + ... "max_volume": {"max": {"property": "volume"}}, + ... }, ... ) >>> for a in res: ... # loop over aggregates in different groups @@ -798,37 +804,37 @@ def create_coordinate_reference_systems( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> custom_crs = CoordinateReferenceSystemWrite( - ... srid = 121111, + ... srid=121111, ... wkt=( - ... 'PROJCS["NTF (Paris) / Lambert zone II",' - ... ' GEOGCS["NTF (Paris)",' - ... ' DATUM["Nouvelle_Triangulation_Francaise_Paris",' - ... ' SPHEROID["Clarke 1880 (IGN)",6378249.2,293.4660212936265,' - ... ' AUTHORITY["EPSG","7011"]],' - ... ' TOWGS84[-168,-60,320,0,0,0,0],' - ... ' AUTHORITY["EPSG","6807"]],' - ... ' PRIMEM["Paris",2.33722917,' - ... ' AUTHORITY["EPSG","8903"]],' - ... ' UNIT["grad",0.01570796326794897,' - ... ' AUTHORITY["EPSG","9105"]], ' - ... ' AUTHORITY["EPSG","4807"]],' - ... ' PROJECTION["Lambert_Conformal_Conic_1SP"],' - ... ' PARAMETER["latitude_of_origin",52],' - ... ' PARAMETER["central_meridian",0],' - ... ' PARAMETER["scale_factor",0.99987742],' - ... ' PARAMETER["false_easting",600000],' - ... ' PARAMETER["false_northing",2200000],' - ... ' UNIT["metre",1,' - ... ' AUTHORITY["EPSG","9001"]],' - ... ' AXIS["X",EAST],' - ... ' AXIS["Y",NORTH],' - ... ' AUTHORITY["EPSG","27572"]]' + ... 'PROJCS["NTF (Paris) / Lambert zone II",' + ... ' GEOGCS["NTF (Paris)",' + ... ' DATUM["Nouvelle_Triangulation_Francaise_Paris",' + ... ' SPHEROID["Clarke 1880 (IGN)",6378249.2,293.4660212936265,' + ... ' AUTHORITY["EPSG","7011"]],' + ... " TOWGS84[-168,-60,320,0,0,0,0]," + ... ' AUTHORITY["EPSG","6807"]],' + ... ' PRIMEM["Paris",2.33722917,' + ... ' AUTHORITY["EPSG","8903"]],' + ... ' UNIT["grad",0.01570796326794897,' + ... ' AUTHORITY["EPSG","9105"]], ' + ... ' AUTHORITY["EPSG","4807"]],' + ... ' PROJECTION["Lambert_Conformal_Conic_1SP"],' + ... ' PARAMETER["latitude_of_origin",52],' + ... ' PARAMETER["central_meridian",0],' + ... ' PARAMETER["scale_factor",0.99987742],' + ... ' PARAMETER["false_easting",600000],' + ... ' PARAMETER["false_northing",2200000],' + ... ' UNIT["metre",1,' + ... ' AUTHORITY["EPSG","9001"]],' + ... ' AXIS["X",EAST],' + ... ' AXIS["Y",NORTH],' + ... ' AUTHORITY["EPSG","27572"]]' ... ), ... proj_string=( - ... '+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 ' - ... '+x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 ' - ... '+towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs' - ... ) + ... "+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 " + ... "+x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515 " + ... "+towgs84=-168,-60,320,0,0,0,0 +pm=paris +units=m +no_defs" + ... ), ... ) >>> crs = client.geospatial.create_coordinate_reference_systems(custom_crs) """ @@ -892,8 +898,14 @@ def put_raster( >>> feature_type = ... >>> feature = ... >>> raster_property_name = ... - >>> metadata = client.geospatial.put_raster(feature_type.external_id, feature.external_id, - ... raster_property_name, "XYZ", 3857, file) + >>> metadata = client.geospatial.put_raster( + ... feature_type.external_id, + ... feature.external_id, + ... raster_property_name, + ... "XYZ", + ... 3857, + ... file, + ... ) """ return run_sync( self.__async_client.geospatial.put_raster( @@ -928,7 +940,9 @@ def delete_raster(self, feature_type_external_id: str, feature_external_id: str, >>> feature_type = ... >>> feature = ... >>> raster_property_name = ... - >>> client.geospatial.delete_raster(feature_type.external_id, feature.external_id, raster_property_name) + >>> client.geospatial.delete_raster( + ... feature_type.external_id, feature.external_id, raster_property_name + ... ) """ return run_sync( self.__async_client.geospatial.delete_raster( @@ -977,8 +991,13 @@ def get_raster( >>> feature_type = ... >>> feature = ... >>> raster_property_name = ... - >>> raster_data = client.geospatial.get_raster(feature_type.external_id, feature.external_id, - ... raster_property_name, "XYZ", {"SIGNIFICANT_DIGITS": "4"}) + >>> raster_data = client.geospatial.get_raster( + ... feature_type.external_id, + ... feature.external_id, + ... raster_property_name, + ... "XYZ", + ... {"SIGNIFICANT_DIGITS": "4"}, + ... ) """ return run_sync( self.__async_client.geospatial.get_raster( @@ -1009,10 +1028,18 @@ def compute(self, output: dict[str, GeospatialComputeFunction]) -> GeospatialCom Compute the transformation of an ewkt geometry from one SRID to another: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.geospatial import GeospatialGeometryTransformComputeFunction, GeospatialGeometryValueComputeFunction + >>> from cognite.client.data_classes.geospatial import ( + ... GeospatialGeometryTransformComputeFunction, + ... GeospatialGeometryValueComputeFunction, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> compute_function = GeospatialGeometryTransformComputeFunction(GeospatialGeometryValueComputeFunction("SRID=4326;POLYGON((0 0,10 0,10 10,0 10,0 0))"), srid=23031) - >>> compute_result = client.geospatial.compute(output = {"output": compute_function}) + >>> compute_function = GeospatialGeometryTransformComputeFunction( + ... GeospatialGeometryValueComputeFunction( + ... "SRID=4326;POLYGON((0 0,10 0,10 10,0 10,0 0))" + ... ), + ... srid=23031, + ... ) + >>> compute_result = client.geospatial.compute(output={"output": compute_function}) """ return run_sync(self.__async_client.geospatial.compute(output=output)) diff --git a/cognite/client/_sync_api/hosted_extractors/destinations.py b/cognite/client/_sync_api/hosted_extractors/destinations.py index 6d0221b4b7..d729e231b7 100644 --- a/cognite/client/_sync_api/hosted_extractors/destinations.py +++ b/cognite/client/_sync_api/hosted_extractors/destinations.py @@ -80,11 +80,13 @@ def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.hosted_extractors.destinations.retrieve('myDestination') + >>> res = client.hosted_extractors.destinations.retrieve("myDestination") Get multiple destinations by id: - >>> res = client.hosted_extractors.destinations.retrieve(["myDestination", "myDestination2"], ignore_unknown_ids=True) + >>> res = client.hosted_extractors.destinations.retrieve( + ... ["myDestination", "myDestination2"], ignore_unknown_ids=True + ... ) """ return run_sync( self.__async_client.hosted_extractors.destinations.retrieve( @@ -139,10 +141,17 @@ def create(self, items: DestinationWrite | Sequence[DestinationWrite]) -> Destin Create new destination: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.hosted_extractors import DestinationWrite, SessionWrite + >>> from cognite.client.data_classes.hosted_extractors import ( + ... DestinationWrite, + ... SessionWrite, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> destination = DestinationWrite(external_id='my_dest', credentials=SessionWrite("my_nonce"), target_data_set_id=123) + >>> destination = DestinationWrite( + ... external_id="my_dest", + ... credentials=SessionWrite("my_nonce"), + ... target_data_set_id=123, + ... ) >>> res = client.hosted_extractors.destinations.create(destination) """ return run_sync(self.__async_client.hosted_extractors.destinations.create(items=items)) @@ -184,7 +193,7 @@ def update( >>> from cognite.client.data_classes.hosted_extractors import DestinationUpdate >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> destination = DestinationUpdate('my_dest').target_data_set_id.set(123) + >>> destination = DestinationUpdate("my_dest").target_data_set_id.set(123) >>> res = client.hosted_extractors.destinations.update(destination) """ return run_sync(self.__async_client.hosted_extractors.destinations.update(items=items, mode=mode)) @@ -216,6 +225,6 @@ def list(self, limit: int | None = DEFAULT_LIMIT_READ) -> DestinationList: Iterate over chunks of destinations to reduce memory load: >>> for destination_list in client.hosted_extractors.destinations(chunk_size=25): - ... destination_list # do something with the destinationss + ... destination_list # do something with the destinationss """ return run_sync(self.__async_client.hosted_extractors.destinations.list(limit=limit)) diff --git a/cognite/client/_sync_api/hosted_extractors/jobs.py b/cognite/client/_sync_api/hosted_extractors/jobs.py index c24a4b6f53..642b99533b 100644 --- a/cognite/client/_sync_api/hosted_extractors/jobs.py +++ b/cognite/client/_sync_api/hosted_extractors/jobs.py @@ -79,11 +79,13 @@ def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.hosted_extractors.jobs.retrieve('myJob') + >>> res = client.hosted_extractors.jobs.retrieve("myJob") Get multiple jobs by id: - >>> res = client.hosted_extractors.jobs.retrieve(["myJob", "myOtherJob"], ignore_unknown_ids=True) + >>> res = client.hosted_extractors.jobs.retrieve( + ... ["myJob", "myOtherJob"], ignore_unknown_ids=True + ... ) """ return run_sync( self.__async_client.hosted_extractors.jobs.retrieve( @@ -137,7 +139,9 @@ def create(self, items: JobWrite | Sequence[JobWrite]) -> Job | JobList: >>> from cognite.client.data_classes.hosted_extractors import EventHubSourceWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> job_write = EventHubSourceWrite('my_event_hub', 'http://myeventhub.com', "My EventHub", 'my_key', 'my_value') + >>> job_write = EventHubSourceWrite( + ... "my_event_hub", "http://myeventhub.com", "My EventHub", "my_key", "my_value" + ... ) >>> job = client.hosted_extractors.jobs.create(job_write) """ return run_sync(self.__async_client.hosted_extractors.jobs.create(items=items)) @@ -179,7 +183,7 @@ def update( >>> from cognite.client.data_classes.hosted_extractors import EventHubSourceUpdate >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> job = EventHubSourceUpdate('my_event_hub').event_hub_name.set("My Updated EventHub") + >>> job = EventHubSourceUpdate("my_event_hub").event_hub_name.set("My Updated EventHub") >>> updated_job = client.hosted_extractors.jobs.update(job) """ return run_sync(self.__async_client.hosted_extractors.jobs.update(items=items, mode=mode)) @@ -211,7 +215,7 @@ def list(self, limit: int | None = DEFAULT_LIMIT_READ) -> JobList: Iterate over chunks of jobs to reduce memory load: >>> for job_list in client.hosted_extractors.jobs(chunk_size=25): - ... job_list # do something with the jobs + ... job_list # do something with the jobs """ return run_sync(self.__async_client.hosted_extractors.jobs.list(limit=limit)) diff --git a/cognite/client/_sync_api/hosted_extractors/mappings.py b/cognite/client/_sync_api/hosted_extractors/mappings.py index 0585790ad4..c3bcdfa4dc 100644 --- a/cognite/client/_sync_api/hosted_extractors/mappings.py +++ b/cognite/client/_sync_api/hosted_extractors/mappings.py @@ -75,11 +75,13 @@ def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.hosted_extractors.mappings.retrieve('myMapping') + >>> res = client.hosted_extractors.mappings.retrieve("myMapping") Get multiple mappings by id: - >>> res = client.hosted_extractors.mappings.retrieve(["myMapping", "myMapping2"], ignore_unknown_ids=True) + >>> res = client.hosted_extractors.mappings.retrieve( + ... ["myMapping", "myMapping2"], ignore_unknown_ids=True + ... ) """ return run_sync( self.__async_client.hosted_extractors.mappings.retrieve( @@ -137,7 +139,12 @@ def create(self, items: MappingWrite | Sequence[MappingWrite]) -> Mapping | Mapp >>> from cognite.client.data_classes.hosted_extractors import MappingWrite, CustomMapping >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> mapping = MappingWrite(external_id="my_mapping", mapping=CustomMapping("some expression"), published=True, input="json") + >>> mapping = MappingWrite( + ... external_id="my_mapping", + ... mapping=CustomMapping("some expression"), + ... published=True, + ... input="json", + ... ) >>> res = client.hosted_extractors.mappings.create(mapping) """ return run_sync(self.__async_client.hosted_extractors.mappings.create(items=items)) @@ -168,7 +175,7 @@ def update( >>> from cognite.client.data_classes.hosted_extractors import MappingUpdate >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> mapping = MappingUpdate('my_mapping').published.set(False) + >>> mapping = MappingUpdate("my_mapping").published.set(False) >>> res = client.hosted_extractors.mappings.update(mapping) """ return run_sync(self.__async_client.hosted_extractors.mappings.update(items=items)) @@ -200,6 +207,6 @@ def list(self, limit: int | None = DEFAULT_LIMIT_READ) -> MappingList: Iterate over chunks of mappings to reduce memory load: >>> for mapping_list in client.hosted_extractors.mappings(chunk_size=25): - ... mapping_list # do something with the mappings + ... mapping_list # do something with the mappings """ return run_sync(self.__async_client.hosted_extractors.mappings.list(limit=limit)) diff --git a/cognite/client/_sync_api/hosted_extractors/sources.py b/cognite/client/_sync_api/hosted_extractors/sources.py index 989f21073b..527bd6d472 100644 --- a/cognite/client/_sync_api/hosted_extractors/sources.py +++ b/cognite/client/_sync_api/hosted_extractors/sources.py @@ -74,11 +74,13 @@ def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.hosted_extractors.sources.retrieve('myMQTTSource') + >>> res = client.hosted_extractors.sources.retrieve("myMQTTSource") Get multiple sources by id: - >>> res = client.hosted_extractors.sources.retrieve(["myMQTTSource", "MyEventHubSource"], ignore_unknown_ids=True) + >>> res = client.hosted_extractors.sources.retrieve( + ... ["myMQTTSource", "MyEventHubSource"], ignore_unknown_ids=True + ... ) """ return run_sync( self.__async_client.hosted_extractors.sources.retrieve( @@ -135,7 +137,9 @@ def create(self, items: SourceWrite | Sequence[SourceWrite]) -> Source | SourceL >>> from cognite.client.data_classes.hosted_extractors import EventHubSourceWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> source = EventHubSourceWrite('my_event_hub', 'http://myeventhub.com', "My EventHub", 'my_key', 'my_value') + >>> source = EventHubSourceWrite( + ... "my_event_hub", "http://myeventhub.com", "My EventHub", "my_key", "my_value" + ... ) >>> res = client.hosted_extractors.sources.create(source) """ return run_sync(self.__async_client.hosted_extractors.sources.create(items=items)) @@ -177,7 +181,9 @@ def update( >>> from cognite.client.data_classes.hosted_extractors import EventHubSourceUpdate >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> source = EventHubSourceUpdate('my_event_hub').event_hub_name.set("My Updated EventHub") + >>> source = EventHubSourceUpdate("my_event_hub").event_hub_name.set( + ... "My Updated EventHub" + ... ) >>> res = client.hosted_extractors.sources.update(source) """ return run_sync(self.__async_client.hosted_extractors.sources.update(items=items, mode=mode)) @@ -209,6 +215,6 @@ def list(self, limit: int | None = DEFAULT_LIMIT_READ) -> SourceList: Iterate over chunks of sources to reduce memory load: >>> for source_list in client.hosted_extractors.sources(chunk_size=25): - ... source_list # do something with the sources + ... source_list # do something with the sources """ return run_sync(self.__async_client.hosted_extractors.sources.list(limit=limit)) diff --git a/cognite/client/_sync_api/iam/__init__.py b/cognite/client/_sync_api/iam/__init__.py index 9fb0b09923..763e82fd94 100644 --- a/cognite/client/_sync_api/iam/__init__.py +++ b/cognite/client/_sync_api/iam/__init__.py @@ -76,26 +76,28 @@ def compare_capabilities( >>> to_check = [ ... AssetsAcl( ... actions=[AssetsAcl.Action.Read, AssetsAcl.Action.Write], - ... scope=AssetsAcl.Scope.All()), + ... scope=AssetsAcl.Scope.All(), + ... ), ... EventsAcl( ... actions=[EventsAcl.Action.Write], ... scope=EventsAcl.Scope.DataSet([123]), - ... )] + ... ), + ... ] >>> missing = client.iam.compare_capabilities( - ... existing_capabilities=my_groups, - ... desired_capabilities=to_check) + ... existing_capabilities=my_groups, desired_capabilities=to_check + ... ) >>> if missing: ... pass # do something Capabilities can also be passed as dictionaries: >>> to_check = [ - ... {'assetsAcl': {'actions': ['READ', 'WRITE'], 'scope': {'all': {}}}}, - ... {'eventsAcl': {'actions': ['WRITE'], 'scope': {'datasetScope': {'ids': [123]}}}}, + ... {"assetsAcl": {"actions": ["READ", "WRITE"], "scope": {"all": {}}}}, + ... {"eventsAcl": {"actions": ["WRITE"], "scope": {"datasetScope": {"ids": [123]}}}}, ... ] >>> missing = client.iam.compare_capabilities( - ... existing_capabilities=my_groups, - ... desired_capabilities=to_check) + ... existing_capabilities=my_groups, desired_capabilities=to_check + ... ) You may also load capabilities from a dict-representation directly into ACLs (access-control list) by using ``Capability.load``. This will also ensure that the capabilities are valid. @@ -129,19 +131,21 @@ def verify_capabilities(self, desired_capabilities: ComparableCapability) -> lis >>> to_check = [ ... AssetsAcl( ... actions=[AssetsAcl.Action.Read, AssetsAcl.Action.Write], - ... scope=AssetsAcl.Scope.All()), + ... scope=AssetsAcl.Scope.All(), + ... ), ... EventsAcl( ... actions=[EventsAcl.Action.Write], ... scope=EventsAcl.Scope.DataSet([123]), - ... )] + ... ), + ... ] >>> if missing := client.iam.verify_capabilities(to_check): ... pass # do something Capabilities can also be passed as dictionaries: >>> to_check = [ - ... {'assetsAcl': {'actions': ['READ', 'WRITE'], 'scope': {'all': {}}}}, - ... {'eventsAcl': {'actions': ['WRITE'], 'scope': {'datasetScope': {'ids': [123]}}}}, + ... {"assetsAcl": {"actions": ["READ", "WRITE"], "scope": {"all": {}}}}, + ... {"eventsAcl": {"actions": ["WRITE"], "scope": {"datasetScope": {"ids": [123]}}}}, ... ] >>> missing = client.iam.verify_capabilities(to_check) diff --git a/cognite/client/_sync_api/iam/groups.py b/cognite/client/_sync_api/iam/groups.py index abf904b194..0464705d02 100644 --- a/cognite/client/_sync_api/iam/groups.py +++ b/cognite/client/_sync_api/iam/groups.py @@ -74,7 +74,8 @@ def create(self, group: Group | GroupWrite | Sequence[Group] | Sequence[GroupWri >>> # async_client = AsyncCogniteClient() # another option >>> my_capabilities = [ ... AssetsAcl([AssetsAcl.Action.Read], AssetsAcl.Scope.All()), - ... EventsAcl([EventsAcl.Action.Write], EventsAcl.Scope.DataSet([123, 456]))] + ... EventsAcl([EventsAcl.Action.Write], EventsAcl.Scope.DataSet([123, 456])), + ... ] >>> my_group = GroupWrite(name="My Group", capabilities=my_capabilities) >>> res = client.iam.groups.create(my_group) @@ -85,7 +86,8 @@ def create(self, group: Group | GroupWrite | Sequence[Group] | Sequence[GroupWri >>> grp = GroupWrite( ... name="Externally managed group", ... capabilities=my_capabilities, - ... source_id="b7c9a5a4...") + ... source_id="b7c9a5a4...", + ... ) >>> res = client.iam.groups.create(grp) Create a group whose members are managed internally by Cognite. This group may grant access through @@ -102,7 +104,8 @@ def create(self, group: Group | GroupWrite | Sequence[Group] | Sequence[GroupWri >>> user_list_group = GroupWrite( ... name="Specfic users only", ... capabilities=my_capabilities, - ... members=["XRsSD1k3mTIKG", "M0SxY6bM9Jl"]) + ... members=["XRsSD1k3mTIKG", "M0SxY6bM9Jl"], + ... ) >>> res = client.iam.groups.create([user_list_group, all_group]) Capabilities are often defined in configuration files, like YAML or JSON. You may convert capabilities @@ -111,8 +114,8 @@ def create(self, group: Group | GroupWrite | Sequence[Group] | Sequence[GroupWri >>> from cognite.client.data_classes.capabilities import Capability >>> unparsed_capabilities = [ - ... {'assetsAcl': {'actions': ['READ', 'WRITE'], 'scope': {'all': {}}}}, - ... {'eventsAcl': {'actions': ['WRITE'], 'scope': {'datasetScope': {'ids': [123]}}}}, + ... {"assetsAcl": {"actions": ["READ", "WRITE"], "scope": {"all": {}}}}, + ... {"eventsAcl": {"actions": ["WRITE"], "scope": {"datasetScope": {"ids": [123]}}}}, ... ] >>> acls = [Capability.load(cap) for cap in unparsed_capabilities] >>> group = GroupWrite(name="Another group", capabilities=acls) diff --git a/cognite/client/_sync_api/labels.py b/cognite/client/_sync_api/labels.py index a839ac9f24..96d2badfb2 100644 --- a/cognite/client/_sync_api/labels.py +++ b/cognite/client/_sync_api/labels.py @@ -160,7 +160,7 @@ def list( Iterate over chunks of label definitions to reduce memory load: >>> for label_list in client.labels(chunk_size=2500): - ... label_list # do something with the type definitions + ... label_list # do something with the type definitions """ return run_sync( self.__async_client.labels.list( @@ -201,7 +201,12 @@ def create( >>> from cognite.client.data_classes import LabelDefinitionWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> labels = [LabelDefinitionWrite(external_id="ROTATING_EQUIPMENT", name="Rotating equipment"), LabelDefinitionWrite(external_id="PUMP", name="pump")] + >>> labels = [ + ... LabelDefinitionWrite( + ... external_id="ROTATING_EQUIPMENT", name="Rotating equipment" + ... ), + ... LabelDefinitionWrite(external_id="PUMP", name="pump"), + ... ] >>> res = client.labels.create(labels) """ return run_sync(self.__async_client.labels.create(label=label)) diff --git a/cognite/client/_sync_api/postgres_gateway/tables.py b/cognite/client/_sync_api/postgres_gateway/tables.py index 33ffb1de78..dd7a0f9671 100644 --- a/cognite/client/_sync_api/postgres_gateway/tables.py +++ b/cognite/client/_sync_api/postgres_gateway/tables.py @@ -74,8 +74,11 @@ def create(self, username: str, items: pg.TableWrite | Sequence[pg.TableWrite]) >>> from cognite.client.data_classes.postgres_gateway import ViewTableWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> table = ViewTableWrite(tablename="myCustom", options=ViewId(space="mySpace", external_id="myExternalId", version="v1")) - >>> res = client.postgres_gateway.tables.create("myUserName",table) + >>> table = ViewTableWrite( + ... tablename="myCustom", + ... options=ViewId(space="mySpace", external_id="myExternalId", version="v1"), + ... ) + >>> res = client.postgres_gateway.tables.create("myUserName", table) """ return run_sync(self.__async_client.postgres_gateway.tables.create(username=username, items=items)) @@ -113,11 +116,13 @@ def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.postgres_gateway.tables.retrieve("myUserName", 'myCustom') + >>> res = client.postgres_gateway.tables.retrieve("myUserName", "myCustom") Get multiple custom tables by id: - >>> res = client.postgres_gateway.tables.retrieve("myUserName", ["myCustom", "myCustom2"]) + >>> res = client.postgres_gateway.tables.retrieve( + ... "myUserName", ["myCustom", "myCustom2"] + ... ) """ return run_sync( self.__async_client.postgres_gateway.tables.retrieve( @@ -187,7 +192,7 @@ def list( Iterate over chunks of tables to reduce memory load: >>> for table_list in client.postgres_gateway.tables(chunk_size=25): - ... table_list # do something with the custom tables + ... table_list # do something with the custom tables """ return run_sync( self.__async_client.postgres_gateway.tables.list( diff --git a/cognite/client/_sync_api/postgres_gateway/users.py b/cognite/client/_sync_api/postgres_gateway/users.py index d1dfc8d9c8..fb02976402 100644 --- a/cognite/client/_sync_api/postgres_gateway/users.py +++ b/cognite/client/_sync_api/postgres_gateway/users.py @@ -79,13 +79,16 @@ def create(self, user: UserWrite | Sequence[UserWrite]) -> UserCreated | UserCre >>> import os >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.postgres_gateway import UserWrite, SessionCredentials + >>> from cognite.client.data_classes.postgres_gateway import ( + ... UserWrite, + ... SessionCredentials, + ... ) >>> from cognite.client.data_classes import ClientCredentials >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> session = client.iam.sessions.create( ... ClientCredentials(os.environ["IDP_CLIENT_ID"], os.environ["IDP_CLIENT_SECRET"]), - ... session_type="CLIENT_CREDENTIALS" + ... session_type="CLIENT_CREDENTIALS", ... ) >>> user = UserWrite(credentials=SessionCredentials(nonce=session.nonce)) >>> res = client.postgres_gateway.users.create(user) @@ -116,15 +119,20 @@ def update(self, items: UserUpdate | UserWrite | Sequence[UserUpdate | UserWrite >>> import os >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.postgres_gateway import UserUpdate, SessionCredentials + >>> from cognite.client.data_classes.postgres_gateway import ( + ... UserUpdate, + ... SessionCredentials, + ... ) >>> from cognite.client.data_classes import ClientCredentials >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> session = client.iam.sessions.create( ... ClientCredentials(os.environ["IDP_CLIENT_ID"], os.environ["IDP_CLIENT_SECRET"]), - ... session_type="CLIENT_CREDENTIALS" + ... session_type="CLIENT_CREDENTIALS", + ... ) + >>> update = UserUpdate("myUser").credentials.set( + ... SessionCredentials(nonce=session.nonce) ... ) - >>> update = UserUpdate('myUser').credentials.set(SessionCredentials(nonce=session.nonce)) >>> res = client.postgres_gateway.users.update(update) """ return run_sync(self.__async_client.postgres_gateway.users.update(items=items)) @@ -216,6 +224,6 @@ def list(self, limit: int = DEFAULT_LIMIT_READ) -> UserList: Iterate over chunks of users to reduce memory load: >>> for user_list in client.postgres_gateway.users(chunk_size=25): - ... user_list # do something with the users + ... user_list # do something with the users """ return run_sync(self.__async_client.postgres_gateway.users.list(limit=limit)) diff --git a/cognite/client/_sync_api/raw/databases.py b/cognite/client/_sync_api/raw/databases.py index 676e056801..d5e0188a66 100644 --- a/cognite/client/_sync_api/raw/databases.py +++ b/cognite/client/_sync_api/raw/databases.py @@ -120,6 +120,6 @@ def list(self, limit: int | None = DEFAULT_LIMIT_READ) -> DatabaseList: Iterate over chunks of databases to reduce memory load: >>> for db_list in client.raw.databases(chunk_size=2500): - ... db_list # do something with the dbs + ... db_list # do something with the dbs """ return run_sync(self.__async_client.raw.databases.list(limit=limit)) diff --git a/cognite/client/_sync_api/raw/rows.py b/cognite/client/_sync_api/raw/rows.py index 4fa4041f70..f40c88eb59 100644 --- a/cognite/client/_sync_api/raw/rows.py +++ b/cognite/client/_sync_api/raw/rows.py @@ -152,8 +152,10 @@ def insert( >>> from cognite.client.data_classes import RowWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> rows = [RowWrite(key="r1", columns={"col1": "val1", "col2": "val1"}), - ... RowWrite(key="r2", columns={"col1": "val2", "col2": "val2"})] + >>> rows = [ + ... RowWrite(key="r1", columns={"col1": "val1", "col2": "val1"}), + ... RowWrite(key="r2", columns={"col1": "val2", "col2": "val2"}), + ... ] >>> client.raw.rows.insert("db1", "table1", rows) You may also insert a dictionary directly: @@ -195,10 +197,9 @@ def insert_dataframe( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> df = pd.DataFrame( - ... {"col-a": [1, 3, None], "col-b": [2, -1, 9]}, - ... index=["r1", "r2", "r3"]) - >>> res = client.raw.rows.insert_dataframe( - ... "db1", "table1", df, dropna=True) + ... {"col-a": [1, 3, None], "col-b": [2, -1, 9]}, index=["r1", "r2", "r3"] + ... ) + >>> res = client.raw.rows.insert_dataframe("db1", "table1", df, dropna=True) """ return run_sync( self.__async_client.raw.rows.insert_dataframe( @@ -355,7 +356,7 @@ def list( Iterate through all rows one-by-one to reduce memory load (no concurrency used): - >>> for row in client.raw.rows("db1", "t1", columns=["col1","col2"]): + >>> for row in client.raw.rows("db1", "t1", columns=["col1", "col2"]): ... val1 = row["col1"] # You may access the data directly ... val2 = row.get("col2") # ...or use '.get' when keys can be missing diff --git a/cognite/client/_sync_api/raw/tables.py b/cognite/client/_sync_api/raw/tables.py index 0f400570b0..a491eeff5a 100644 --- a/cognite/client/_sync_api/raw/tables.py +++ b/cognite/client/_sync_api/raw/tables.py @@ -123,6 +123,6 @@ def list(self, db_name: str, limit: int | None = DEFAULT_LIMIT_READ) -> raw.Tabl Iterate over chunks of tables to reduce memory load: >>> for table_list in client.raw.tables(db_name="db1", chunk_size=25): - ... table_list # do something with the tables + ... table_list # do something with the tables """ return run_sync(self.__async_client.raw.tables.list(db_name=db_name, limit=limit)) diff --git a/cognite/client/_sync_api/relationships.py b/cognite/client/_sync_api/relationships.py index 9d827e9f3d..18949c9348 100644 --- a/cognite/client/_sync_api/relationships.py +++ b/cognite/client/_sync_api/relationships.py @@ -310,7 +310,7 @@ def create( ... target_external_id="target_ext_id", ... target_type="event", ... confidence=0.1, - ... data_set_id=1234 + ... data_set_id=1234, ... ) >>> flowrel2 = RelationshipWrite( ... external_id="flow_2", @@ -319,9 +319,9 @@ def create( ... target_external_id="target_ext_id", ... target_type="event", ... confidence=0.1, - ... data_set_id=1234 + ... data_set_id=1234, ... ) - >>> res = client.relationships.create([flowrel1,flowrel2]) + >>> res = client.relationships.create([flowrel1, flowrel2]) """ return run_sync(self.__async_client.relationships.create(relationship=relationship)) @@ -363,7 +363,11 @@ def update( Perform a partial update on a relationship, setting a source_external_id and a confidence: >>> from cognite.client.data_classes import RelationshipUpdate - >>> my_update = RelationshipUpdate(external_id="flow_1").source_external_id.set("alternate_source").confidence.set(0.97) + >>> my_update = ( + ... RelationshipUpdate(external_id="flow_1") + ... .source_external_id.set("alternate_source") + ... .confidence.set(0.97) + ... ) >>> res1 = client.relationships.update(my_update) >>> # Remove an already set optional field like so >>> another_update = RelationshipUpdate(external_id="flow_1").confidence.set(None) @@ -427,9 +431,11 @@ def upsert( ... source_external_id="new_source", ... source_type="asset", ... target_external_id="new_target", - ... target_type="event" + ... target_type="event", + ... ) + >>> res = client.relationships.upsert( + ... [existing_relationship, new_relationship], mode="replace" ... ) - >>> res = client.relationships.upsert([existing_relationship, new_relationship], mode="replace") """ return run_sync(self.__async_client.relationships.upsert(item=item, mode=mode)) @@ -447,7 +453,7 @@ def delete(self, external_id: str | SequenceNotStr[str], ignore_unknown_ids: boo >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.relationships.delete(external_id=["a","b"]) + >>> client.relationships.delete(external_id=["a", "b"]) """ return run_sync( self.__async_client.relationships.delete(external_id=external_id, ignore_unknown_ids=ignore_unknown_ids) diff --git a/cognite/client/_sync_api/sequence_data.py b/cognite/client/_sync_api/sequence_data.py index 75d7b7220a..5977dbcf6b 100644 --- a/cognite/client/_sync_api/sequence_data.py +++ b/cognite/client/_sync_api/sequence_data.py @@ -56,27 +56,32 @@ def insert( ... SequenceWrite( ... columns=[ ... SequenceColumnWrite(value_type="STRING", external_id="col_a"), - ... SequenceColumnWrite(value_type="DOUBLE", external_id ="col_b") + ... SequenceColumnWrite(value_type="DOUBLE", external_id="col_b"), ... ], ... ) ... ) - >>> data = [(1, ['pi',3.14]), (2, ['e',2.72]) ] - >>> client.sequences.data.insert(columns=["col_a","col_b"], rows=data, id=1) + >>> data = [(1, ["pi", 3.14]), (2, ["e", 2.72])] + >>> client.sequences.data.insert(columns=["col_a", "col_b"], rows=data, id=1) They can also be provided as a list of API-style objects with a rowNumber and values field: - >>> data = [{"rowNumber": 123, "values": ['str',3]}, {"rowNumber": 456, "values": ["bar",42]} ] - >>> client.sequences.data.insert(data, id=1, columns=["col_a","col_b"]) # implicit columns are retrieved from metadata + >>> data = [ + ... {"rowNumber": 123, "values": ["str", 3]}, + ... {"rowNumber": 456, "values": ["bar", 42]}, + ... ] + >>> client.sequences.data.insert( + ... data, id=1, columns=["col_a", "col_b"] + ... ) # implicit columns are retrieved from metadata Or they can be a given as a dictionary with row number as the key, and the value is the data to be inserted at that row: - >>> data = {123 : ['str',3], 456 : ['bar',42] } - >>> client.sequences.data.insert(columns=['stringColumn','intColumn'], rows=data, id=1) + >>> data = {123: ["str", 3], 456: ["bar", 42]} + >>> client.sequences.data.insert(columns=["stringColumn", "intColumn"], rows=data, id=1) Finally, they can be a SequenceData object retrieved from another request. In this case columns from this object are used as well. - >>> data = client.sequences.data.retrieve(id=2,start=0,end=10) - >>> client.sequences.data.insert(rows=data, id=1,columns=None) + >>> data = client.sequences.data.retrieve(id=2, start=0, end=10) + >>> client.sequences.data.insert(rows=data, id=1, columns=None) """ return run_sync( self.__async_client.sequences.data.insert(rows=rows, columns=columns, id=id, external_id=external_id) @@ -104,7 +109,7 @@ def insert_dataframe( >>> import pandas as pd >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> df = pd.DataFrame({'col_a': [1, 2, 3], 'col_b': [4, 5, 6]}, index=[1, 2, 3]) + >>> df = pd.DataFrame({"col_a": [1, 2, 3], "col_b": [4, 5, 6]}, index=[1, 2, 3]) >>> client.sequences.data.insert_dataframe(df, id=123) """ return run_sync( @@ -129,7 +134,7 @@ def delete(self, rows: typing.Sequence[int], id: int | None = None, external_id: >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.sequences.data.delete(id=1, rows=[1,2,42]) + >>> client.sequences.data.delete(id=1, rows=[1, 2, 42]) """ return run_sync(self.__async_client.sequences.data.delete(rows=rows, id=id, external_id=external_id)) @@ -251,10 +256,14 @@ def retrieve( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> res = client.sequences.data.retrieve(id=1) - >>> tuples = [(r,v) for r,v in res.items()] # You can use this iterator in for loops and list comprehensions, - >>> single_value = res[23] # ... get the values at a single row number, - >>> col = res.get_column(external_id='columnExtId') # ... get the array of values for a specific column, - >>> df = res.to_pandas() # ... or convert the result to a dataframe + >>> tuples = [ + ... (r, v) for r, v in res.items() + ... ] # You can use this iterator in for loops and list comprehensions, + >>> single_value = res[23] # ... get the values at a single row number, + >>> col = res.get_column( + ... external_id="columnExtId" + ... ) # ... get the array of values for a specific column, + >>> df = res.to_pandas() # ... or convert the result to a dataframe """ return run_sync( self.__async_client.sequences.data.retrieve( diff --git a/cognite/client/_sync_api/sequences.py b/cognite/client/_sync_api/sequences.py index 2983af24f8..0ed9c4b5aa 100644 --- a/cognite/client/_sync_api/sequences.py +++ b/cognite/client/_sync_api/sequences.py @@ -258,7 +258,9 @@ def aggregate_cardinality_values( >>> from cognite.client.data_classes.sequences import SequenceProperty >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> count = client.sequences.aggregate_cardinality_values(SequenceProperty.metadata_key("efficiency")) + >>> count = client.sequences.aggregate_cardinality_values( + ... SequenceProperty.metadata_key("efficiency") + ... ) Count the number of timezones (metadata key) for sequences with the word "critical" in the description in your CDF project, but exclude timezones from america: @@ -270,7 +272,8 @@ def aggregate_cardinality_values( >>> timezone_count = client.sequences.aggregate_cardinality_values( ... SequenceProperty.metadata_key("timezone"), ... advanced_filter=is_critical, - ... aggregate_filter=not_america) + ... aggregate_filter=not_america, + ... ) """ return run_sync( self.__async_client.sequences.aggregate_cardinality_values( @@ -340,7 +343,9 @@ def aggregate_unique_values( >>> from cognite.client.data_classes.sequences import SequenceProperty >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> result = client.sequences.aggregate_unique_values(SequenceProperty.metadata_key("timezone")) + >>> result = client.sequences.aggregate_unique_values( + ... SequenceProperty.metadata_key("timezone") + ... ) >>> print(result.unique) Get the different metadata keys with count used for sequences created after 2020-01-01 in your CDF project: @@ -349,8 +354,12 @@ def aggregate_unique_values( >>> from cognite.client.data_classes.sequences import SequenceProperty >>> from cognite.client.utils import timestamp_to_ms >>> from datetime import datetime - >>> created_after_2020 = filters.Range(SequenceProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.sequences.aggregate_unique_values(SequenceProperty.metadata, advanced_filter=created_after_2020) + >>> created_after_2020 = filters.Range( + ... SequenceProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.sequences.aggregate_unique_values( + ... SequenceProperty.metadata, advanced_filter=created_after_2020 + ... ) >>> print(result.unique) Get the different metadata keys with count for sequences updated after 2020-01-01 in your CDF project, but exclude all metadata keys that @@ -359,8 +368,14 @@ def aggregate_unique_values( >>> from cognite.client.data_classes.sequences import SequenceProperty >>> from cognite.client.data_classes import aggregations as aggs, filters >>> not_test = aggs.Not(aggs.Prefix("test")) - >>> created_after_2020 = filters.Range(SequenceProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.sequences.aggregate_unique_values(SequenceProperty.metadata, advanced_filter=created_after_2020, aggregate_filter=not_test) + >>> created_after_2020 = filters.Range( + ... SequenceProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.sequences.aggregate_unique_values( + ... SequenceProperty.metadata, + ... advanced_filter=created_after_2020, + ... aggregate_filter=not_test, + ... ) >>> print(result.unique) """ return run_sync( @@ -431,14 +446,20 @@ def create( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> column_def = [ - ... SequenceColumnWrite(value_type="STRING", external_id="user", description="some description"), - ... SequenceColumnWrite(value_type="DOUBLE", external_id="amount") + ... SequenceColumnWrite( + ... value_type="STRING", external_id="user", description="some description" + ... ), + ... SequenceColumnWrite(value_type="DOUBLE", external_id="amount"), ... ] - >>> seq = client.sequences.create(SequenceWrite(external_id="my_sequence", columns=column_def)) + >>> seq = client.sequences.create( + ... SequenceWrite(external_id="my_sequence", columns=column_def) + ... ) Create a new sequence with the same column specifications as an existing sequence: - >>> seq2 = client.sequences.create(SequenceWrite(external_id="my_copied_sequence", columns=column_def)) + >>> seq2 = client.sequences.create( + ... SequenceWrite(external_id="my_copied_sequence", columns=column_def) + ... ) """ return run_sync(self.__async_client.sequences.create(sequence=sequence)) @@ -463,7 +484,7 @@ def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.sequences.delete(id=[1,2,3], external_id="3") + >>> client.sequences.delete(id=[1, 2, 3], external_id="3") """ return run_sync( self.__async_client.sequences.delete(id=id, external_id=external_id, ignore_unknown_ids=ignore_unknown_ids) @@ -512,7 +533,11 @@ def update( Perform a partial update on a sequence, updating the description and adding a new field to metadata: >>> from cognite.client.data_classes import SequenceUpdate - >>> my_update = SequenceUpdate(id=1).description.set("New description").metadata.add({"key": "value"}) + >>> my_update = ( + ... SequenceUpdate(id=1) + ... .description.set("New description") + ... .metadata.add({"key": "value"}) + ... ) >>> res = client.sequences.update(my_update) **Updating column definitions** @@ -524,7 +549,9 @@ def update( >>> from cognite.client.data_classes import SequenceUpdate, SequenceColumnWrite >>> >>> my_update = SequenceUpdate(id=1).columns.add( - ... SequenceColumnWrite(value_type ="STRING",external_id="user", description ="some description") + ... SequenceColumnWrite( + ... value_type="STRING", external_id="user", description="some description" + ... ) ... ) >>> res = client.sequences.update(my_update) @@ -533,8 +560,10 @@ def update( >>> from cognite.client.data_classes import SequenceUpdate, SequenceColumnWrite >>> >>> column_def = [ - ... SequenceColumnWrite(value_type ="STRING",external_id="user", description ="some description"), - ... SequenceColumnWrite(value_type="DOUBLE", external_id="amount") + ... SequenceColumnWrite( + ... value_type="STRING", external_id="user", description="some description" + ... ), + ... SequenceColumnWrite(value_type="DOUBLE", external_id="amount"), ... ] >>> my_update = SequenceUpdate(id=1).columns.add(column_def) >>> res = client.sequences.update(my_update) @@ -550,7 +579,9 @@ def update( >>> from cognite.client.data_classes import SequenceUpdate >>> - >>> my_update = SequenceUpdate(id=1).columns.remove(["col_external_id1","col_external_id2"]) + >>> my_update = SequenceUpdate(id=1).columns.remove( + ... ["col_external_id1", "col_external_id2"] + ... ) >>> res = client.sequences.update(my_update) Update existing columns: @@ -558,8 +589,12 @@ def update( >>> from cognite.client.data_classes import SequenceUpdate, SequenceColumnUpdate >>> >>> column_updates = [ - ... SequenceColumnUpdate(external_id="col_external_id_1").external_id.set("new_col_external_id"), - ... SequenceColumnUpdate(external_id="col_external_id_2").description.set("my new description"), + ... SequenceColumnUpdate(external_id="col_external_id_1").external_id.set( + ... "new_col_external_id" + ... ), + ... SequenceColumnUpdate(external_id="col_external_id_2").description.set( + ... "my new description" + ... ), ... ] >>> my_update = SequenceUpdate(id=1).columns.modify(column_updates) >>> res = client.sequences.update(my_update) @@ -606,7 +641,7 @@ def upsert( >>> new_sequence = SequenceWrite( ... external_id="new_sequence", ... description="New sequence", - ... columns=[SequenceColumnWrite(external_id="col1", value_type="STRING")] + ... columns=[SequenceColumnWrite(external_id="col1", value_type="STRING")], ... ) >>> res = client.sequences.upsert([existing_sequence, new_sequence], mode="replace") """ @@ -712,7 +747,7 @@ def list( Iterate over chunks of sequences to reduce memory load: >>> for seq_list in client.sequences(chunk_size=2500): - ... seq_list # do something with the sequences + ... seq_list # do something with the sequences Using advanced filter, find all sequences that have a metadata key 'timezone' starting with 'Europe', and sort by external id ascending: @@ -728,20 +763,25 @@ def list( for filtering and sorting, you can also use the `SequenceProperty` and `SortableSequenceProperty` Enums. >>> from cognite.client.data_classes import filters - >>> from cognite.client.data_classes.sequences import SequenceProperty, SortableSequenceProperty + >>> from cognite.client.data_classes.sequences import ( + ... SequenceProperty, + ... SortableSequenceProperty, + ... ) >>> in_timezone = filters.Prefix(SequenceProperty.metadata_key("timezone"), "Europe") >>> res = client.sequences.list( - ... advanced_filter=in_timezone, - ... sort=(SortableSequenceProperty.external_id, "asc")) + ... advanced_filter=in_timezone, sort=(SortableSequenceProperty.external_id, "asc") + ... ) Combine filter and advanced filter: >>> from cognite.client.data_classes import filters >>> not_instrument_lvl5 = filters.And( - ... filters.ContainsAny("labels", ["Level5"]), - ... filters.Not(filters.ContainsAny("labels", ["Instrument"])) + ... filters.ContainsAny("labels", ["Level5"]), + ... filters.Not(filters.ContainsAny("labels", ["Instrument"])), + ... ) + >>> res = client.sequences.list( + ... asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5 ... ) - >>> res = client.sequences.list(asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5) """ return run_sync( self.__async_client.sequences.list( diff --git a/cognite/client/_sync_api/simulators/integrations.py b/cognite/client/_sync_api/simulators/integrations.py index b4d5239578..51b1447aef 100644 --- a/cognite/client/_sync_api/simulators/integrations.py +++ b/cognite/client/_sync_api/simulators/integrations.py @@ -129,6 +129,6 @@ def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.simulators.integrations.delete(ids=[1,2,3], external_ids="foo") + >>> client.simulators.integrations.delete(ids=[1, 2, 3], external_ids="foo") """ return run_sync(self.__async_client.simulators.integrations.delete(ids=ids, external_ids=external_ids)) diff --git a/cognite/client/_sync_api/simulators/models.py b/cognite/client/_sync_api/simulators/models.py index f68bb251a6..7a7e24137f 100644 --- a/cognite/client/_sync_api/simulators/models.py +++ b/cognite/client/_sync_api/simulators/models.py @@ -69,10 +69,7 @@ def list( >>> from cognite.client.data_classes.simulators.filters import PropertySort >>> res = client.simulators.models.list( ... simulator_external_ids=["simulator_external_id"], - ... sort=PropertySort( - ... property="createdTime", - ... order="asc" - ... ) + ... sort=PropertySort(property="createdTime", order="asc"), ... ) """ return run_sync( @@ -119,7 +116,7 @@ def retrieve( >>> res = client.simulators.models.retrieve(external_ids="model_external_id") Get multiple simulator models by ids: - >>> res = client.simulators.models.retrieve(ids=[1,2]) + >>> res = client.simulators.models.retrieve(ids=[1, 2]) Get multiple simulator models by external ids: >>> res = client.simulators.models.retrieve( @@ -201,13 +198,19 @@ def create(self, items: SimulatorModelWrite | Sequence[SimulatorModelWrite]) -> >>> # async_client = AsyncCogniteClient() # another option >>> models = [ ... SimulatorModelWrite( - ... name="model1", simulator_external_id="sim1", type="SteadyState", - ... data_set_id=1, external_id="model_external_id" + ... name="model1", + ... simulator_external_id="sim1", + ... type="SteadyState", + ... data_set_id=1, + ... external_id="model_external_id", ... ), ... SimulatorModelWrite( - ... name="model2", simulator_external_id="sim2", type="SteadyState", - ... data_set_id=2, external_id="model_external_id2" - ... ) + ... name="model2", + ... simulator_external_id="sim2", + ... type="SteadyState", + ... data_set_id=2, + ... external_id="model_external_id2", + ... ), ... ] >>> res = client.simulators.models.create(models) """ @@ -228,7 +231,7 @@ def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.simulators.models.delete(ids=[1,2,3], external_ids="model_external_id") + >>> client.simulators.models.delete(ids=[1, 2, 3], external_ids="model_external_id") """ return run_sync(self.__async_client.simulators.models.delete(ids=ids, external_ids=external_ids)) diff --git a/cognite/client/_sync_api/simulators/models_revisions.py b/cognite/client/_sync_api/simulators/models_revisions.py index e0ceae7d24..ed6c40fc3e 100644 --- a/cognite/client/_sync_api/simulators/models_revisions.py +++ b/cognite/client/_sync_api/simulators/models_revisions.py @@ -75,7 +75,7 @@ def list( ... created_time=TimestampRange(min=0, max=1000000), ... last_updated_time=TimestampRange(min=0, max=1000000), ... sort=PropertySort(order="asc", property="createdTime"), - ... limit=10 + ... limit=10, ... ) """ return run_sync( @@ -129,7 +129,7 @@ def retrieve( ... ) Get multiple simulator model revisions by ids: - >>> res = client.simulators.models.revisions.retrieve(ids=[1,2]) + >>> res = client.simulators.models.revisions.retrieve(ids=[1, 2]) Get multiple simulator model revisions by external ids: >>> res = client.simulators.models.revisions.retrieve( @@ -226,7 +226,11 @@ def create( Examples: Create new simulator model revisions: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.simulators import SimulatorModelRevisionWrite, SimulatorModelDependencyFileId, SimulatorModelRevisionDependency + >>> from cognite.client.data_classes.simulators import ( + ... SimulatorModelRevisionWrite, + ... SimulatorModelDependencyFileId, + ... SimulatorModelRevisionDependency, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> revisions = [ @@ -239,7 +243,7 @@ def create( ... external_id="revision2", ... file_id=2, ... model_external_id="a_2", - ... external_dependencies = [ + ... external_dependencies=[ ... SimulatorModelRevisionDependency( ... file=SimulatorModelDependencyFileId(id=123), ... arguments={ @@ -247,7 +251,7 @@ def create( ... "fieldB": "value2", ... }, ... ) - ... ] + ... ], ... ), ... ] >>> res = client.simulators.models.revisions.create(revisions) diff --git a/cognite/client/_sync_api/simulators/routine_revisions.py b/cognite/client/_sync_api/simulators/routine_revisions.py index 019fd6639d..d5b8ef7e6b 100644 --- a/cognite/client/_sync_api/simulators/routine_revisions.py +++ b/cognite/client/_sync_api/simulators/routine_revisions.py @@ -327,13 +327,11 @@ def list( ... routine_external_ids=["routine_1"], ... all_versions=True, ... sort=PropertySort(order="asc", property="createdTime"), - ... include_all_fields=True + ... include_all_fields=True, ... ) List simulator routine revisions by kind: - >>> res = client.simulators.routines.revisions.list( - ... kind="long" - ... ) + >>> res = client.simulators.routines.revisions.list(kind="long") """ return run_sync( self.__async_client.simulators.routines.revisions.list( diff --git a/cognite/client/_sync_api/simulators/routines.py b/cognite/client/_sync_api/simulators/routines.py index d83551cfe7..4d4814b7df 100644 --- a/cognite/client/_sync_api/simulators/routines.py +++ b/cognite/client/_sync_api/simulators/routines.py @@ -125,7 +125,7 @@ def create( ... simulator_integration_external_id="integration_ext_id_2", ... model_external_id="model_ext_id_2", ... kind="long", - ... ) + ... ), ... ] >>> res = client.simulators.routines.create(routines) """ @@ -148,7 +148,7 @@ def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.simulators.routines.delete(ids=[1,2,3], external_ids="foo") + >>> client.simulators.routines.delete(ids=[1, 2, 3], external_ids="foo") """ return run_sync(self.__async_client.simulators.routines.delete(ids=ids, external_ids=external_ids)) @@ -190,16 +190,11 @@ def list( >>> from cognite.client.data_classes.simulators.filters import PropertySort >>> res = client.simulators.routines.list( ... simulator_integration_external_ids=["integration_ext_id"], - ... sort=PropertySort( - ... property="createdTime", - ... order="desc" - ... ) + ... sort=PropertySort(property="createdTime", order="desc"), ... ) Filter on routine kind: - >>> res = client.simulators.routines.list( - ... kind="long" - ... ) + >>> res = client.simulators.routines.list(kind="long") """ return run_sync( self.__async_client.simulators.routines.list( @@ -280,8 +275,7 @@ def run( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> run = client.simulators.routines.run( - ... routine_external_id="routine1", - ... log_severity="Debug" + ... routine_external_id="routine1", log_severity="Debug" ... ) Create new simulation run using routine and model revision external IDs: diff --git a/cognite/client/_sync_api/simulators/runs.py b/cognite/client/_sync_api/simulators/runs.py index 77c1f7f072..2688735302 100644 --- a/cognite/client/_sync_api/simulators/runs.py +++ b/cognite/client/_sync_api/simulators/runs.py @@ -177,8 +177,7 @@ def list( Filter runs by status and simulator external ids: >>> res = client.simulators.runs.list( - ... simulator_external_ids=["PROSPER", "DWSIM"], - ... status="success" + ... simulator_external_ids=["PROSPER", "DWSIM"], status="success" ... ) Filter runs by time ranges: diff --git a/cognite/client/_sync_api/synthetic_time_series.py b/cognite/client/_sync_api/synthetic_time_series.py index 6c734ea3a3..a3ac727512 100644 --- a/cognite/client/_sync_api/synthetic_time_series.py +++ b/cognite/client/_sync_api/synthetic_time_series.py @@ -110,9 +110,8 @@ def query( ... + ts{space:'my-space',externalId:'my-ts-xid'} ... ''' >>> dps = client.time_series.data.synthetic.query( - ... expressions=expression, - ... start="2w-ago", - ... end="now") + ... expressions=expression, start="2w-ago", end="now" + ... ) You can also specify variables for an easier query syntax: @@ -124,14 +123,15 @@ def query( ... "C": NodeId("my-space", "my-ts-xid"), ... } >>> dps = client.time_series.data.synthetic.query( - ... expressions="A+B+C", start="2w-ago", end="2w-ahead", variables=variables) + ... expressions="A+B+C", start="2w-ago", end="2w-ahead", variables=variables + ... ) Use sympy to build complex expressions: >>> from sympy import symbols, cos, sin >>> x, y = symbols("x y") >>> dps = client.time_series.data.synthetic.query( - ... [sin(x), y*cos(x)], + ... [sin(x), y * cos(x)], ... start="2w-ago", ... end="now", ... variables={x: "foo", y: "bar"}, diff --git a/cognite/client/_sync_api/three_d/asset_mapping.py b/cognite/client/_sync_api/three_d/asset_mapping.py index 716cd2e74a..a0c1359462 100644 --- a/cognite/client/_sync_api/three_d/asset_mapping.py +++ b/cognite/client/_sync_api/three_d/asset_mapping.py @@ -65,7 +65,8 @@ def list( >>> from cognite.client.data_classes import BoundingBox3D >>> bbox = BoundingBox3D(min=[0.0, 0.0, 0.0], max=[1.0, 1.0, 1.0]) >>> res = client.three_d.asset_mappings.list( - ... model_id=1, revision_id=1, intersects_bounding_box=bbox) + ... model_id=1, revision_id=1, intersects_bounding_box=bbox + ... ) """ return run_sync( self.__async_client.three_d.asset_mappings.list( @@ -120,7 +121,9 @@ def create( >>> my_mapping = ThreeDAssetMappingWrite(node_id=1, asset_id=1) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.three_d.asset_mappings.create(model_id=1, revision_id=1, asset_mapping=my_mapping) + >>> res = client.three_d.asset_mappings.create( + ... model_id=1, revision_id=1, asset_mapping=my_mapping + ... ) """ return run_sync( self.__async_client.three_d.asset_mappings.create( @@ -147,7 +150,9 @@ def delete( >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> mapping_to_delete = client.three_d.asset_mappings.list(model_id=1, revision_id=1)[0] - >>> res = client.three_d.asset_mappings.delete(model_id=1, revision_id=1, asset_mapping=mapping_to_delete) + >>> res = client.three_d.asset_mappings.delete( + ... model_id=1, revision_id=1, asset_mapping=mapping_to_delete + ... ) """ return run_sync( self.__async_client.three_d.asset_mappings.delete( diff --git a/cognite/client/_sync_api/three_d/models.py b/cognite/client/_sync_api/three_d/models.py index 3202a18df6..1747f7ee12 100644 --- a/cognite/client/_sync_api/three_d/models.py +++ b/cognite/client/_sync_api/three_d/models.py @@ -103,7 +103,7 @@ def list(self, published: bool | None = None, limit: int | None = DEFAULT_LIMIT_ Iterate over chunks of 3d models to reduce memory load: >>> for model in client.three_d.models(chunk_size=50): - ... model # do something with the 3d model + ... model # do something with the 3d model """ return run_sync(self.__async_client.three_d.models.list(published=published, limit=limit)) @@ -146,7 +146,9 @@ def create( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.three_d.models.create(name="My Model", data_set_id=1, metadata={"key1": "value1", "key2": "value2"}) + >>> res = client.three_d.models.create( + ... name="My Model", data_set_id=1, metadata={"key1": "value1", "key2": "value2"} + ... ) Create multiple new 3D Models: @@ -154,8 +156,14 @@ def create( >>> from cognite.client.data_classes import ThreeDModelWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> my_model = ThreeDModelWrite(name="My Model", data_set_id=1, metadata={"key1": "value1", "key2": "value2"}) - >>> my_other_model = ThreeDModelWrite(name="My Other Model", data_set_id=1, metadata={"key1": "value1", "key2": "value2"}) + >>> my_model = ThreeDModelWrite( + ... name="My Model", data_set_id=1, metadata={"key1": "value1", "key2": "value2"} + ... ) + >>> my_other_model = ThreeDModelWrite( + ... name="My Other Model", + ... data_set_id=1, + ... metadata={"key1": "value1", "key2": "value2"}, + ... ) >>> res = client.three_d.models.create([my_model, my_other_model]) """ return run_sync( diff --git a/cognite/client/_sync_api/three_d/revisions.py b/cognite/client/_sync_api/three_d/revisions.py index 63bc7ca2af..0891bb17a2 100644 --- a/cognite/client/_sync_api/three_d/revisions.py +++ b/cognite/client/_sync_api/three_d/revisions.py @@ -183,7 +183,11 @@ def update( Perform a partial update on a revision, updating the published property and adding a new field to metadata: >>> from cognite.client.data_classes import ThreeDModelRevisionUpdate - >>> my_update = ThreeDModelRevisionUpdate(id=1).published.set(False).metadata.add({"key": "value"}) + >>> my_update = ( + ... ThreeDModelRevisionUpdate(id=1) + ... .published.set(False) + ... .metadata.add({"key": "value"}) + ... ) >>> res = client.three_d.revisions.update(model_id=1, item=my_update) """ return run_sync(self.__async_client.three_d.revisions.update(model_id=model_id, item=item, mode=mode)) @@ -308,7 +312,17 @@ def filter_nodes( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.three_d.revisions.filter_nodes(model_id=1, revision_id=1, properties={ "PDMS": { "Area": ["AB76", "AB77", "AB78"], "Type": ["PIPE", "BEND", "PIPESUP"] } }, limit=10) + >>> res = client.three_d.revisions.filter_nodes( + ... model_id=1, + ... revision_id=1, + ... properties={ + ... "PDMS": { + ... "Area": ["AB76", "AB77", "AB78"], + ... "Type": ["PIPE", "BEND", "PIPESUP"], + ... } + ... }, + ... limit=10, + ... ) """ return run_sync( self.__async_client.three_d.revisions.filter_nodes( @@ -338,7 +352,9 @@ def list_ancestor_nodes( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.three_d.revisions.list_ancestor_nodes(model_id=1, revision_id=1, node_id=5, limit=10) + >>> res = client.three_d.revisions.list_ancestor_nodes( + ... model_id=1, revision_id=1, node_id=5, limit=10 + ... ) """ return run_sync( self.__async_client.three_d.revisions.list_ancestor_nodes( diff --git a/cognite/client/_sync_api/time_series.py b/cognite/client/_sync_api/time_series.py index e878ce8820..c0c35c2c7a 100644 --- a/cognite/client/_sync_api/time_series.py +++ b/cognite/client/_sync_api/time_series.py @@ -307,7 +307,8 @@ def aggregate_cardinality_values( >>> timezone_count = client.time_series.aggregate_cardinality_values( ... TimeSeriesProperty.metadata_key("timezone"), ... advanced_filter=is_critical, - ... aggregate_filter=not_america) + ... aggregate_filter=not_america, + ... ) """ return run_sync( self.__async_client.time_series.aggregate_cardinality_values( @@ -341,7 +342,9 @@ def aggregate_cardinality_properties( >>> from cognite.client.data_classes.time_series import TimeSeriesProperty >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> key_count = client.time_series.aggregate_cardinality_properties(TimeSeriesProperty.metadata) + >>> key_count = client.time_series.aggregate_cardinality_properties( + ... TimeSeriesProperty.metadata + ... ) """ return run_sync( self.__async_client.time_series.aggregate_cardinality_properties( @@ -376,7 +379,9 @@ def aggregate_unique_values( >>> from cognite.client.data_classes.time_series import TimeSeriesProperty >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> result = client.time_series.aggregate_unique_values(TimeSeriesProperty.metadata_key("timezone")) + >>> result = client.time_series.aggregate_unique_values( + ... TimeSeriesProperty.metadata_key("timezone") + ... ) >>> print(result.unique) Get the different units with count used for time series created after 2020-01-01 in your CDF project: @@ -385,8 +390,12 @@ def aggregate_unique_values( >>> from cognite.client.data_classes.time_series import TimeSeriesProperty >>> from cognite.client.utils import timestamp_to_ms >>> from datetime import datetime - >>> created_after_2020 = filters.Range(TimeSeriesProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.time_series.aggregate_unique_values(TimeSeriesProperty.unit, advanced_filter=created_after_2020) + >>> created_after_2020 = filters.Range( + ... TimeSeriesProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.time_series.aggregate_unique_values( + ... TimeSeriesProperty.unit, advanced_filter=created_after_2020 + ... ) >>> print(result.unique) Get the different units with count for time series updated after 2020-01-01 in your CDF project, but exclude all units that @@ -395,8 +404,14 @@ def aggregate_unique_values( >>> from cognite.client.data_classes.time_series import TimeSeriesProperty >>> from cognite.client.data_classes import aggregations as aggs, filters >>> not_test = aggs.Not(aggs.Prefix("test")) - >>> created_after_2020 = filters.Range(TimeSeriesProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) - >>> result = client.time_series.aggregate_unique_values(TimeSeriesProperty.unit, advanced_filter=created_after_2020, aggregate_filter=not_test) + >>> created_after_2020 = filters.Range( + ... TimeSeriesProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1)) + ... ) + >>> result = client.time_series.aggregate_unique_values( + ... TimeSeriesProperty.unit, + ... advanced_filter=created_after_2020, + ... aggregate_filter=not_test, + ... ) >>> print(result.unique) """ return run_sync( @@ -466,7 +481,9 @@ def create( >>> from cognite.client.data_classes import TimeSeriesWrite >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> ts = client.time_series.create(TimeSeriesWrite(name="my_ts", data_set_id=123, external_id="foo")) + >>> ts = client.time_series.create( + ... TimeSeriesWrite(name="my_ts", data_set_id=123, external_id="foo") + ... ) """ return run_sync(self.__async_client.time_series.create(time_series=time_series)) @@ -491,7 +508,7 @@ def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.time_series.delete(id=[1,2,3], external_id="3") + >>> client.time_series.delete(id=[1, 2, 3], external_id="3") """ return run_sync( self.__async_client.time_series.delete( @@ -545,7 +562,11 @@ def update( Perform a partial update on a time series, updating the description and adding a new field to metadata: >>> from cognite.client.data_classes import TimeSeriesUpdate - >>> my_update = TimeSeriesUpdate(id=1).description.set("New description").metadata.add({"key": "value"}) + >>> my_update = ( + ... TimeSeriesUpdate(id=1) + ... .description.set("New description") + ... .metadata.add({"key": "value"}) + ... ) >>> res = client.time_series.update(my_update) Perform a partial update on a time series by instance id. @@ -603,8 +624,12 @@ def upsert( >>> # async_client = AsyncCogniteClient() # another option >>> existing_time_series = client.time_series.retrieve(id=1) >>> existing_time_series.description = "New description" - >>> new_time_series = TimeSeriesWrite(external_id="new_timeSeries", description="New timeSeries") - >>> res = client.time_series.upsert([existing_time_series, new_time_series], mode="replace") + >>> new_time_series = TimeSeriesWrite( + ... external_id="new_timeSeries", description="New timeSeries" + ... ) + >>> res = client.time_series.upsert( + ... [existing_time_series, new_time_series], mode="replace" + ... ) """ return run_sync(self.__async_client.time_series.upsert(item=item, mode=mode)) @@ -641,7 +666,7 @@ def search( Search for all time series connected to asset with id 123: - >>> res = client.time_series.search(filter={"asset_ids":[123]}) + >>> res = client.time_series.search(filter={"asset_ids": [123]}) """ return run_sync( self.__async_client.time_series.search( @@ -723,14 +748,16 @@ def list( Iterate over chunks of time series to reduce memory load: >>> for ts_list in client.time_series(chunk_size=2500): - ... ts_list # do something with the time series + ... ts_list # do something with the time series Using advanced filter, find all time series that have a metadata key 'timezone' starting with 'Europe', and sort by external id ascending: >>> from cognite.client.data_classes import filters >>> in_timezone = filters.Prefix(["metadata", "timezone"], "Europe") - >>> res = client.time_series.list(advanced_filter=in_timezone, sort=("external_id", "asc")) + >>> res = client.time_series.list( + ... advanced_filter=in_timezone, sort=("external_id", "asc") + ... ) Note that you can check the API documentation above to see which properties you can filter on with which filters. @@ -739,20 +766,25 @@ def list( for filtering and sorting, you can also use the `TimeSeriesProperty` and `SortableTimeSeriesProperty` Enums. >>> from cognite.client.data_classes import filters - >>> from cognite.client.data_classes.time_series import TimeSeriesProperty, SortableTimeSeriesProperty + >>> from cognite.client.data_classes.time_series import ( + ... TimeSeriesProperty, + ... SortableTimeSeriesProperty, + ... ) >>> in_timezone = filters.Prefix(TimeSeriesProperty.metadata_key("timezone"), "Europe") >>> res = client.time_series.list( - ... advanced_filter=in_timezone, - ... sort=(SortableTimeSeriesProperty.external_id, "asc")) + ... advanced_filter=in_timezone, sort=(SortableTimeSeriesProperty.external_id, "asc") + ... ) Combine filter and advanced filter: >>> from cognite.client.data_classes import filters >>> not_instrument_lvl5 = filters.And( - ... filters.ContainsAny("labels", ["Level5"]), - ... filters.Not(filters.ContainsAny("labels", ["Instrument"])) + ... filters.ContainsAny("labels", ["Level5"]), + ... filters.Not(filters.ContainsAny("labels", ["Instrument"])), + ... ) + >>> res = client.time_series.list( + ... asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5 ... ) - >>> res = client.time_series.list(asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5) """ return run_sync( self.__async_client.time_series.list( diff --git a/cognite/client/_sync_api/transformations/__init__.py b/cognite/client/_sync_api/transformations/__init__.py index 554ecb1ffe..d25364fdf1 100644 --- a/cognite/client/_sync_api/transformations/__init__.py +++ b/cognite/client/_sync_api/transformations/__init__.py @@ -164,8 +164,15 @@ def create( Create new transformations: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes import TransformationWrite, TransformationDestination - >>> from cognite.client.data_classes.transformations.common import ViewInfo, EdgeType, DataModelInfo + >>> from cognite.client.data_classes import ( + ... TransformationWrite, + ... TransformationDestination, + ... ) + >>> from cognite.client.data_classes.transformations.common import ( + ... ViewInfo, + ... EdgeType, + ... DataModelInfo, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> transformations = [ @@ -364,7 +371,9 @@ def retrieve_multiple( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.transformations.retrieve_multiple(ids=[1,2,3], external_ids=['transform-1','transform-2']) + >>> res = client.transformations.retrieve_multiple( + ... ids=[1, 2, 3], external_ids=["transform-1", "transform-2"] + ... ) """ return run_sync( self.__async_client.transformations.retrieve_multiple( @@ -418,7 +427,11 @@ def update( Perform a partial update on a transformation, updating the query and making it private: >>> from cognite.client.data_classes import TransformationUpdate - >>> my_update = TransformationUpdate(id=1).query.set("SELECT * FROM _cdf.assets").is_public.set(False) + >>> my_update = ( + ... TransformationUpdate(id=1) + ... .query.set("SELECT * FROM _cdf.assets") + ... .is_public.set(False) + ... ) >>> res = client.transformations.update(my_update) Update the session used for reading (source) and writing (destination) when authenticating for all @@ -430,7 +443,7 @@ def update( >>> new_nonce = NonceCredentials( ... session_id=new_session.id, ... nonce=new_session.nonce, - ... cdf_project_name=client.config.project + ... cdf_project_name=client.config.project, ... ) >>> for tr in to_update: ... tr.source_nonce = new_nonce @@ -548,12 +561,16 @@ def preview( a query that converts one source row to one result row, you may need to increase the `source_limit`. For example, given that you have a query that reads from a raw table with 10,903 rows - >>> result = client.transformations.preview(query="select * from my_raw_db.my_raw_table", limit=None) + >>> result = client.transformations.preview( + ... query="select * from my_raw_db.my_raw_table", limit=None + ... ) >>> print(result.results) # 100 To get all rows, you also need to set the `source_limit` to None: - >>> result = client.transformations.preview(query="select * from my_raw_db.my_raw_table", limit=None, source_limit=None) + >>> result = client.transformations.preview( + ... query="select * from my_raw_db.my_raw_table", limit=None, source_limit=None + ... ) >>> print(result.results) # 10903 """ return run_sync( diff --git a/cognite/client/_sync_api/transformations/notifications.py b/cognite/client/_sync_api/transformations/notifications.py index 25abb62b08..2e1b10f787 100644 --- a/cognite/client/_sync_api/transformations/notifications.py +++ b/cognite/client/_sync_api/transformations/notifications.py @@ -175,6 +175,6 @@ def delete(self, id: int | Sequence[int] | None = None) -> None: >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.transformations.notifications.delete(id=[1,2,3]) + >>> client.transformations.notifications.delete(id=[1, 2, 3]) """ return run_sync(self.__async_client.transformations.notifications.delete(id=id)) diff --git a/cognite/client/_sync_api/transformations/schedules.py b/cognite/client/_sync_api/transformations/schedules.py index b99dbc70bb..ed8e1e0bb2 100644 --- a/cognite/client/_sync_api/transformations/schedules.py +++ b/cognite/client/_sync_api/transformations/schedules.py @@ -204,7 +204,7 @@ def delete( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> client.transformations.schedules.delete(id=[1,2,3], external_id="3") + >>> client.transformations.schedules.delete(id=[1, 2, 3], external_id="3") """ return run_sync( self.__async_client.transformations.schedules.delete( @@ -258,7 +258,9 @@ def update( Perform a partial update on a transformation schedule, updating the interval and unpausing it: >>> from cognite.client.data_classes import TransformationScheduleUpdate - >>> my_update = TransformationScheduleUpdate(id=1).interval.set("0 * * * *").is_paused.set(False) + >>> my_update = ( + ... TransformationScheduleUpdate(id=1).interval.set("0 * * * *").is_paused.set(False) + ... ) >>> res = client.transformations.schedules.update(my_update) """ return run_sync(self.__async_client.transformations.schedules.update(item=item, mode=mode)) diff --git a/cognite/client/_sync_api/units.py b/cognite/client/_sync_api/units.py index a98b49ee18..cbb48e319b 100644 --- a/cognite/client/_sync_api/units.py +++ b/cognite/client/_sync_api/units.py @@ -53,11 +53,11 @@ def retrieve( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.units.retrieve('temperature:deg_c') + >>> res = client.units.retrieve("temperature:deg_c") Retrive units 'temperature:deg_c' and 'pressure:bar': - >>> res = client.units.retrieve(['temperature:deg_c', 'pressure:bar']) + >>> res = client.units.retrieve(["temperature:deg_c", "pressure:bar"]) """ return run_sync( self.__async_client.units.retrieve(external_id=external_id, ignore_unknown_ids=ignore_unknown_ids) @@ -119,11 +119,11 @@ def from_alias( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> unit = client.units.from_alias('cmol / L') + >>> unit = client.units.from_alias("cmol / L") Look up ambiguous alias 'F' by passing quantity 'Temperature': - >>> unit = client.units.from_alias('F', 'Temperature') + >>> unit = client.units.from_alias("F", "Temperature") Search for the closest matching unit of 'kilo watt' (should be 'kilowatt'): diff --git a/cognite/client/_sync_api/vision.py b/cognite/client/_sync_api/vision.py index 108dea352d..67c91420dd 100644 --- a/cognite/client/_sync_api/vision.py +++ b/cognite/client/_sync_api/vision.py @@ -44,7 +44,9 @@ def extract( >>> from cognite.client.data_classes.contextualization import VisionFeature >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> extract_job = client.vision.extract(features=VisionFeature.ASSET_TAG_DETECTION, file_ids=[1]) + >>> extract_job = client.vision.extract( + ... features=VisionFeature.ASSET_TAG_DETECTION, file_ids=[1] + ... ) >>> extract_job.wait_for_completion() >>> for item in extract_job.items: ... predictions = item.predictions diff --git a/cognite/client/_sync_api/workflows/executions.py b/cognite/client/_sync_api/workflows/executions.py index d0d33dd66b..218ad0028e 100644 --- a/cognite/client/_sync_api/workflows/executions.py +++ b/cognite/client/_sync_api/workflows/executions.py @@ -50,7 +50,9 @@ def retrieve_detailed(self, id: str) -> WorkflowExecutionDetailed | None: >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.workflows.executions.retrieve_detailed("000560bc-9080-4286-b242-a27bb4819253") + >>> res = client.workflows.executions.retrieve_detailed( + ... "000560bc-9080-4286-b242-a27bb4819253" + ... ) List workflow executions and retrieve detailed information for the first one: @@ -88,7 +90,9 @@ def run( ... external_id="my_workflow-task1", ... parameters=FunctionTaskParameters( ... external_id="cdf_deployed_function:my_function", - ... data={"workflow_data": "${workflow.input}"})) + ... data={"workflow_data": "${workflow.input}"}, + ... ), + ... ) Tip: You can create a session via the Sessions API, using the client.iam.session.create() method. @@ -160,8 +164,7 @@ def list( Get all workflow executions from the last 24 hours: >>> from cognite.client.utils import timestamp_to_ms - >>> res = client.workflows.executions.list( - ... created_time_start=timestamp_to_ms("1d-ago")) + >>> res = client.workflows.executions.list(created_time_start=timestamp_to_ms("1d-ago")) """ return run_sync( self.__async_client.workflows.executions.list( diff --git a/cognite/client/_sync_api/workflows/tasks.py b/cognite/client/_sync_api/workflows/tasks.py index fb5447c817..bc8dad4fb9 100644 --- a/cognite/client/_sync_api/workflows/tasks.py +++ b/cognite/client/_sync_api/workflows/tasks.py @@ -47,11 +47,15 @@ def update( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> res = client.workflows.tasks.update("000560bc-9080-4286-b242-a27bb4819253", "completed") + >>> res = client.workflows.tasks.update( + ... "000560bc-9080-4286-b242-a27bb4819253", "completed" + ... ) Update task with id '000560bc-9080-4286-b242-a27bb4819253' to status 'failed' with output '{"a": 1, "b": 2}': - >>> res = client.workflows.tasks.update("000560bc-9080-4286-b242-a27bb4819253", "failed", output={"a": 1, "b": 2}) + >>> res = client.workflows.tasks.update( + ... "000560bc-9080-4286-b242-a27bb4819253", "failed", output={"a": 1, "b": 2} + ... ) Trigger workflow, retrieve detailed task execution and update status of the second task (assumed to be async) to 'completed': diff --git a/cognite/client/_sync_api/workflows/triggers.py b/cognite/client/_sync_api/workflows/triggers.py index 0604fb0441..9167c449b6 100644 --- a/cognite/client/_sync_api/workflows/triggers.py +++ b/cognite/client/_sync_api/workflows/triggers.py @@ -50,14 +50,19 @@ def upsert( Create or update a scheduled trigger for a workflow: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.workflows import WorkflowTriggerUpsert, WorkflowScheduledTriggerRule + >>> from cognite.client.data_classes.workflows import ( + ... WorkflowTriggerUpsert, + ... WorkflowScheduledTriggerRule, + ... ) >>> from zoneinfo import ZoneInfo >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> client.workflows.triggers.upsert( ... WorkflowTriggerUpsert( ... external_id="my_trigger", - ... trigger_rule=WorkflowScheduledTriggerRule(cron_expression="0 0 * * *", timezone=ZoneInfo("UTC")), + ... trigger_rule=WorkflowScheduledTriggerRule( + ... cron_expression="0 0 * * *", timezone=ZoneInfo("UTC") + ... ), ... workflow_external_id="my_workflow", ... workflow_version="1", ... input={"a": 1, "b": 2}, @@ -67,8 +72,15 @@ def upsert( Create or update a data modeling trigger for a workflow: - >>> from cognite.client.data_classes.workflows import WorkflowDataModelingTriggerRule, WorkflowTriggerDataModelingQuery - >>> from cognite.client.data_classes.data_modeling.query import NodeResultSetExpression, Select, SourceSelector + >>> from cognite.client.data_classes.workflows import ( + ... WorkflowDataModelingTriggerRule, + ... WorkflowTriggerDataModelingQuery, + ... ) + >>> from cognite.client.data_classes.data_modeling.query import ( + ... NodeResultSetExpression, + ... Select, + ... SourceSelector, + ... ) >>> from cognite.client.data_classes.data_modeling import ViewId >>> from cognite.client.data_classes.filters import Equals >>> view_id = ViewId("my_space_id", "view_external_id", "v1") @@ -77,7 +89,13 @@ def upsert( ... external_id="my_trigger", ... trigger_rule=WorkflowDataModelingTriggerRule( ... data_modeling_query=WorkflowTriggerDataModelingQuery( - ... with_={"timeseries": NodeResultSetExpression(filter=Equals(view_id.as_property_ref("name"), value="my_name"))}, + ... with_={ + ... "timeseries": NodeResultSetExpression( + ... filter=Equals( + ... view_id.as_property_ref("name"), value="my_name" + ... ) + ... ) + ... }, ... select={"timeseries": Select([SourceSelector(view_id, ["name"])])}, ... ), ... batch_size=500, diff --git a/cognite/client/_sync_api/workflows/versions.py b/cognite/client/_sync_api/workflows/versions.py index 998fa03211..8de5b97bc6 100644 --- a/cognite/client/_sync_api/workflows/versions.py +++ b/cognite/client/_sync_api/workflows/versions.py @@ -99,8 +99,10 @@ def upsert( >>> from cognite.client import CogniteClient >>> from cognite.client.data_classes import ( - ... WorkflowVersionUpsert, WorkflowDefinitionUpsert, - ... WorkflowTask, FunctionTaskParameters, + ... WorkflowVersionUpsert, + ... WorkflowDefinitionUpsert, + ... WorkflowTask, + ... FunctionTaskParameters, ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option @@ -112,12 +114,12 @@ def upsert( ... ), ... ) >>> new_version = WorkflowVersionUpsert( - ... workflow_external_id="my_workflow", - ... version="1", - ... workflow_definition=WorkflowDefinitionUpsert( - ... tasks=[function_task], - ... description="This workflow has one step", - ... ), + ... workflow_external_id="my_workflow", + ... version="1", + ... workflow_definition=WorkflowDefinitionUpsert( + ... tasks=[function_task], + ... description="This workflow has one step", + ... ), ... ) >>> res = client.workflows.versions.upsert(new_version) """ @@ -151,7 +153,9 @@ def delete( Delete workflow version "1" of workflow "my workflow" and workflow version "2" of workflow "my workflow 2" using the WorkflowVersionId class: >>> from cognite.client.data_classes import WorkflowVersionId - >>> client.workflows.versions.delete([WorkflowVersionId("my workflow", "1"), WorkflowVersionId("my workflow 2", "2")]) + >>> client.workflows.versions.delete( + ... [WorkflowVersionId("my workflow", "1"), WorkflowVersionId("my workflow 2", "2")] + ... ) """ return run_sync( self.__async_client.workflows.versions.delete( @@ -236,12 +240,12 @@ def list( >>> from cognite.client.data_classes import WorkflowVersionId >>> res = client.workflows.versions.list( - ... [WorkflowVersionId("my_workflow"), WorkflowVersionId("my_workflow_2")]) + ... [WorkflowVersionId("my_workflow"), WorkflowVersionId("my_workflow_2")] + ... ) Get all workflow versions for workflows 'my_workflow' version '1' and 'my_workflow_2' version '2' using tuples: - >>> res = client.workflows.versions.list( - ... [("my_workflow", "1"), ("my_workflow_2", "2")]) + >>> res = client.workflows.versions.list([("my_workflow", "1"), ("my_workflow_2", "2")]) """ return run_sync( self.__async_client.workflows.versions.list(workflow_version_ids=workflow_version_ids, limit=limit) diff --git a/cognite/client/credentials.py b/cognite/client/credentials.py index 64c8a6972a..b11ae91475 100644 --- a/cognite/client/credentials.py +++ b/cognite/client/credentials.py @@ -816,7 +816,7 @@ class OAuthClientCredentials(_OAuthCredentialProviderWithTokenRefresh): ... client_secret=os.environ["OAUTH_CLIENT_SECRET"], ... scopes=["https://greenfield.cognitedata.com/.default"], ... # Any additional IDP-specific token args. e.g. - ... audience="some-audience" + ... audience="some-audience", ... ) """ @@ -918,7 +918,7 @@ def load(cls, config: dict[str, Any] | str) -> OAuthClientCredentials: ... "client_id": "abcd", ... "client_secret": os.environ["OAUTH_CLIENT_SECRET"], ... "scopes": ["https://greenfield.cognitedata.com/.default"], - ... "audience": "some-audience" + ... "audience": "some-audience", ... } >>> credentials = OAuthClientCredentials.load(config) """ diff --git a/cognite/client/data_classes/contextualization.py b/cognite/client/data_classes/contextualization.py index 914ad0dbf0..e353ff05cd 100644 --- a/cognite/client/data_classes/contextualization.py +++ b/cognite/client/data_classes/contextualization.py @@ -1458,7 +1458,10 @@ class DiagramDetectConfig(CogniteResource): Configure a call to digrams detect endpoint: >>> from cognite.client import CogniteClient - >>> from cognite.client.data_classes.contextualization import ConnectionFlags, DiagramDetectConfig + >>> from cognite.client.data_classes.contextualization import ( + ... ConnectionFlags, + ... DiagramDetectConfig, + ... ) >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> config = DiagramDetectConfig( @@ -1466,7 +1469,7 @@ class DiagramDetectConfig(CogniteResource): ... connection_flags=ConnectionFlags( ... no_text_inbetween=True, ... natural_reading_order=True, - ... ) + ... ), ... ) >>> job = client.diagrams.detect(entities=[{"name": "A1"}], file_id=123, config=config) diff --git a/cognite/client/data_classes/filters.py b/cognite/client/data_classes/filters.py index 1090e3567f..e04a82a5e9 100644 --- a/cognite/client/data_classes/filters.py +++ b/cognite/client/data_classes/filters.py @@ -313,14 +313,16 @@ class And(CompoundFilter): >>> from cognite.client.data_classes.filters import And, Equals, In >>> flt = And( ... Equals(("space", "view_xid/version", "some_property"), 42), - ... In(("space", "view_xid/version", "another_property"), ["a", "b", "c"])) + ... In(("space", "view_xid/version", "another_property"), ["a", "b", "c"]), + ... ) - Using the ``View.as_property_ref`` method to reference the property: >>> from cognite.client.data_classes.filters import And, Equals, In >>> flt = And( ... Equals(my_view.as_property_ref("some_property"), 42), - ... In(my_view.as_property_ref("another_property"), ["a", "b", "c"])) + ... In(my_view.as_property_ref("another_property"), ["a", "b", "c"]), + ... ) Using the "&" operator: @@ -349,13 +351,15 @@ class Or(CompoundFilter): >>> from cognite.client.data_classes.filters import Or, Equals, In >>> flt = Or( ... Equals(("space", "view_xid/version", "some_property"), 42), - ... In(("space", "view_xid/version", "another_property"), ["a", "b", "c"])) + ... In(("space", "view_xid/version", "another_property"), ["a", "b", "c"]), + ... ) - Using the ``View.as_property_ref`` method to reference the property: >>> flt = Or( ... Equals(my_view.as_property_ref("some_property"), 42), - ... In(my_view.as_property_ref("another_property"), ["a", "b", "c"])) + ... In(my_view.as_property_ref("another_property"), ["a", "b", "c"]), + ... ) Using the "|" operator: @@ -424,13 +428,15 @@ class Nested(Filter): >>> from cognite.client.data_classes.filters import Nested, Equals >>> flt = Nested( ... scope=("space", "viewA_xid/view_version", "viewB-ID"), - ... filter=Equals(("space", "viewB_xid/view_version", "viewB-Property"), 42)) + ... filter=Equals(("space", "viewB_xid/view_version", "viewB-Property"), 42), + ... ) - Composing the property reference using the ``View.as_property_ref`` method: >>> flt = Nested( ... scope=viewA.as_property_ref("viewB-ID"), - ... filter=Equals(viewB.as_property_ref("viewB-Property"), 42)) + ... filter=Equals(viewB.as_property_ref("viewB-Property"), 42), + ... ) """ _filter_name = "nested" @@ -608,14 +614,18 @@ class Overlaps(Filter): >>> flt = Overlaps( ... ("space", "view_xid/version", "some_start_property"), ... ("space", "view_xid/version", "some_end_property"), - ... gt=42, lt=100) + ... gt=42, + ... lt=100, + ... ) - Composing the property reference using the ``View.as_property_ref`` method: >>> flt = Overlaps( ... my_view.as_property_ref("some_start_property"), ... my_view.as_property_ref("some_end_property"), - ... gt=42, lt=100) + ... gt=42, + ... lt=100, + ... ) """ _filter_name = "overlaps" @@ -893,7 +903,7 @@ class InAssetSubtree(FilterWithPropertyAndValueList): >>> client.documents.aggregate_count( ... filter=filters.InAssetSubtree( ... property=DocumentProperty.asset_external_ids, - ... values=['Plant_1', 'Plant_2'], + ... values=["Plant_1", "Plant_2"], ... ) ... ) """ diff --git a/cognite/client/data_classes/geospatial.py b/cognite/client/data_classes/geospatial.py index 12ac7aa062..ba931d32f2 100644 --- a/cognite/client/data_classes/geospatial.py +++ b/cognite/client/data_classes/geospatial.py @@ -371,10 +371,7 @@ def to_geopandas(self, geometry: str, camel_case: bool = False) -> geopandas.Geo >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> features = client.geospatial.search_features(...) - >>> gdf = features.to_geopandas( - ... geometry="position", - ... camel_case=False - ... ) + >>> gdf = features.to_geopandas(geometry="position", camel_case=False) >>> gdf.head() """ df = self.to_pandas(camel_case) @@ -410,12 +407,16 @@ def from_geopandas( >>> from cognite.client import CogniteClient, AsyncCogniteClient >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option - >>> my_feature_type = ... # some feature type with 'position' and 'temperature' properties + >>> my_feature_type = ( + ... ... + ... ) # some feature type with 'position' and 'temperature' properties >>> my_geodataframe = ... # some geodataframe with 'center_xy', 'temp' and 'id' columns >>> feature_list = FeatureList.from_geopandas(feature_type=my_feature_type, geodataframe=my_geodataframe, >>> external_id_column="id", data_set_id_column="dataSetId", >>> property_column_mapping={'position': 'center_xy', 'temperature': 'temp'}) - >>> created_features = client.geospatial.create_features(my_feature_type.external_id, feature_list) + >>> created_features = client.geospatial.create_features( + ... my_feature_type.external_id, feature_list + ... ) """ features = [] diff --git a/cognite/client/data_classes/transformations/jobs.py b/cognite/client/data_classes/transformations/jobs.py index c1172ee229..4771513efe 100644 --- a/cognite/client/data_classes/transformations/jobs.py +++ b/cognite/client/data_classes/transformations/jobs.py @@ -172,8 +172,8 @@ async def wait_async(self, polling_interval: float = 5, timeout: float | None = >>> client = CogniteClient() >>> # async_client = AsyncCogniteClient() # another option >>> - >>> job1 = client.transformations.run(id = 1, wait = False) - >>> job2 = client.transformations.run(id = 2, wait = False) + >>> job1 = client.transformations.run(id=1, wait=False) + >>> job2 = client.transformations.run(id=2, wait=False) >>> job1.wait() >>> job2.wait() >>> if TransformationJobStatus.FAILED not in [job1.status, job2.status]: @@ -182,15 +182,15 @@ async def wait_async(self, polling_interval: float = 5, timeout: float | None = Wait on transformation for 5 minutes and do something if still running: >>> - >>> job = client.transformations.run(id = 1, wait = False) - >>> job.wait(timeout = 5.0*60) + >>> job = client.transformations.run(id=1, wait=False) + >>> job.wait(timeout=5.0 * 60) >>> match job.status: >>> case TransformationJobStatus.FAILED: - >>> # do something if job failed + >>> # do something if job failed >>> case TransformationJobStatus.COMPLETED: - >>> # do something if job completed successfully + >>> # do something if job completed successfully >>> case _: - >>> # do something if job is still running + >>> # do something if job is still running """ await self.update_async() if timeout is None: diff --git a/cognite/client/data_classes/workflows.py b/cognite/client/data_classes/workflows.py index a7b3080018..6c2e03283f 100644 --- a/cognite/client/data_classes/workflows.py +++ b/cognite/client/data_classes/workflows.py @@ -205,7 +205,7 @@ class FunctionTaskParameters(WorkflowTaskParameters): For example, if you have a workflow containing two tasks, and the external_id of the first task is `task1` then, you can specify the data for the second task as follows: - >>> from cognite.client.data_classes import WorkflowTask, FunctionTaskParameters + >>> from cognite.client.data_classes import WorkflowTask, FunctionTaskParameters >>> task = WorkflowTask( ... external_id="task2", ... parameters=FunctionTaskParameters( @@ -213,7 +213,7 @@ class FunctionTaskParameters(WorkflowTaskParameters): ... data={ ... "workflow_data": "${workflow.input}", ... "task1_input": "${task1.input}", - ... "task1_output": "${task1.output}" + ... "task1_output": "${task1.output}", ... }, ... ), ... ) diff --git a/cognite/client/testing.py b/cognite/client/testing.py index bc1d2e1ea3..981a0a7d55 100644 --- a/cognite/client/testing.py +++ b/cognite/client/testing.py @@ -620,7 +620,7 @@ def monkeypatch_cognite_client() -> Iterator[CogniteClientMock]: >>> c_mock.iam.token.inspect.return_value = TokenInspection( >>> subject="subject", projects=[], capabilities=[] >>> ) - >>> # Init. a new client yields the same mocked client: + >>> # Init. a new client yields the same mocked client: >>> client = CogniteClient() >>> res = client.iam.token.inspect() >>> assert "subject" == res.subject @@ -673,7 +673,7 @@ def monkeypatch_async_cognite_client() -> Iterator[AsyncCogniteClientMock]: >>> c_mock.iam.token.inspect.return_value = TokenInspection( >>> subject="subject", projects=[], capabilities=[] >>> ) - >>> # Init. a new client yields the same mocked client: + >>> # Init. a new client yields the same mocked client: >>> client = AsyncCogniteClient() >>> res = await client.iam.token.inspect() >>> assert "subject" == res.subject diff --git a/cognite/client/utils/_time.py b/cognite/client/utils/_time.py index f1769d18c4..4e0a987282 100644 --- a/cognite/client/utils/_time.py +++ b/cognite/client/utils/_time.py @@ -243,8 +243,8 @@ def timestamp_to_ms(timestamp: int | float | str | datetime) -> int: >>> from datetime import datetime >>> timestamp_to_ms(datetime(2021, 1, 7, 12, 0, 0)) >>> timestamp_to_ms("now") - >>> timestamp_to_ms("2w-ago") # 2 weeks ago - >>> timestamp_to_ms("3d-ahead") # 3 days ahead from now + >>> timestamp_to_ms("2w-ago") # 2 weeks ago + >>> timestamp_to_ms("3d-ahead") # 3 days ahead from now """ if isinstance(timestamp, numbers.Number): # float, int, int64 etc ms = int(timestamp) # type: ignore[arg-type] From b201b225f7dd852edc87f4a52b01be99bc7d3744 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A5kon=20V=2E=20Treider?= Date: Fri, 20 Mar 2026 09:36:26 +0100 Subject: [PATCH 3/3] run sync codegen to update hashes --- cognite/client/_sync_api/agents/agents.py | 2 +- cognite/client/_sync_api/ai/tools/documents.py | 2 +- cognite/client/_sync_api/annotations.py | 2 +- cognite/client/_sync_api/assets.py | 2 +- .../client/_sync_api/data_modeling/containers.py | 2 +- .../client/_sync_api/data_modeling/data_models.py | 2 +- cognite/client/_sync_api/data_modeling/graphql.py | 2 +- .../client/_sync_api/data_modeling/instances.py | 15 ++++++++------- .../_sync_api/data_modeling/space_statistics.py | 2 +- cognite/client/_sync_api/data_modeling/spaces.py | 2 +- cognite/client/_sync_api/data_modeling/views.py | 2 +- cognite/client/_sync_api/data_sets.py | 2 +- cognite/client/_sync_api/datapoints.py | 2 +- .../client/_sync_api/datapoints_subscriptions.py | 2 +- cognite/client/_sync_api/diagrams.py | 2 +- cognite/client/_sync_api/document_preview.py | 2 +- cognite/client/_sync_api/documents.py | 2 +- cognite/client/_sync_api/entity_matching.py | 2 +- cognite/client/_sync_api/events.py | 2 +- .../_sync_api/extractionpipelines/__init__.py | 2 +- .../_sync_api/extractionpipelines/configs.py | 2 +- .../client/_sync_api/extractionpipelines/runs.py | 2 +- cognite/client/_sync_api/files.py | 2 +- cognite/client/_sync_api/functions/__init__.py | 2 +- cognite/client/_sync_api/functions/schedules.py | 2 +- cognite/client/_sync_api/geospatial.py | 2 +- .../_sync_api/hosted_extractors/destinations.py | 2 +- .../client/_sync_api/hosted_extractors/jobs.py | 2 +- .../_sync_api/hosted_extractors/mappings.py | 2 +- .../client/_sync_api/hosted_extractors/sources.py | 2 +- cognite/client/_sync_api/iam/__init__.py | 2 +- cognite/client/_sync_api/iam/groups.py | 2 +- cognite/client/_sync_api/labels.py | 2 +- .../client/_sync_api/postgres_gateway/tables.py | 2 +- .../client/_sync_api/postgres_gateway/users.py | 2 +- cognite/client/_sync_api/raw/databases.py | 2 +- cognite/client/_sync_api/raw/rows.py | 2 +- cognite/client/_sync_api/raw/tables.py | 2 +- cognite/client/_sync_api/relationships.py | 2 +- cognite/client/_sync_api/sequence_data.py | 2 +- cognite/client/_sync_api/sequences.py | 2 +- .../client/_sync_api/simulators/integrations.py | 2 +- cognite/client/_sync_api/simulators/models.py | 2 +- .../_sync_api/simulators/models_revisions.py | 2 +- .../_sync_api/simulators/routine_revisions.py | 2 +- cognite/client/_sync_api/simulators/routines.py | 2 +- cognite/client/_sync_api/simulators/runs.py | 2 +- cognite/client/_sync_api/synthetic_time_series.py | 2 +- cognite/client/_sync_api/three_d/asset_mapping.py | 2 +- cognite/client/_sync_api/three_d/models.py | 2 +- cognite/client/_sync_api/three_d/revisions.py | 2 +- cognite/client/_sync_api/time_series.py | 2 +- .../client/_sync_api/transformations/__init__.py | 2 +- .../_sync_api/transformations/notifications.py | 2 +- .../client/_sync_api/transformations/schedules.py | 2 +- cognite/client/_sync_api/units.py | 2 +- cognite/client/_sync_api/vision.py | 2 +- cognite/client/_sync_api/workflows/executions.py | 2 +- cognite/client/_sync_api/workflows/tasks.py | 2 +- cognite/client/_sync_api/workflows/triggers.py | 2 +- cognite/client/_sync_api/workflows/versions.py | 2 +- 61 files changed, 68 insertions(+), 67 deletions(-) diff --git a/cognite/client/_sync_api/agents/agents.py b/cognite/client/_sync_api/agents/agents.py index 4156e60861..0c9520e9f5 100644 --- a/cognite/client/_sync_api/agents/agents.py +++ b/cognite/client/_sync_api/agents/agents.py @@ -1,6 +1,6 @@ """ =============================================================================== -43a5b979901a5b2c3b5c6fdb3bd8bb67 +74efd4d9ffccd91e350abcb621a40578 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/ai/tools/documents.py b/cognite/client/_sync_api/ai/tools/documents.py index b8fc629092..a06b08fc6b 100644 --- a/cognite/client/_sync_api/ai/tools/documents.py +++ b/cognite/client/_sync_api/ai/tools/documents.py @@ -1,6 +1,6 @@ """ =============================================================================== -c5fabf1e47675fc722ffaa889e3ce86b +9662538ccd2652cf7a4858473413645e This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/annotations.py b/cognite/client/_sync_api/annotations.py index 4073aed6b2..95fc744bcc 100644 --- a/cognite/client/_sync_api/annotations.py +++ b/cognite/client/_sync_api/annotations.py @@ -1,6 +1,6 @@ """ =============================================================================== -33bc1c77d566344c6095061469b6c5a8 +91c009d17e4fc01099ebce8bf198babf This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/assets.py b/cognite/client/_sync_api/assets.py index fe142f7a68..deb6d2bdbd 100644 --- a/cognite/client/_sync_api/assets.py +++ b/cognite/client/_sync_api/assets.py @@ -1,6 +1,6 @@ """ =============================================================================== -cc20c7b0db972e7498b0f53498d073bd +62111ab91d0c470f704e057cf41bbee2 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/data_modeling/containers.py b/cognite/client/_sync_api/data_modeling/containers.py index 91ed7802c5..c1c6b508c7 100644 --- a/cognite/client/_sync_api/data_modeling/containers.py +++ b/cognite/client/_sync_api/data_modeling/containers.py @@ -1,6 +1,6 @@ """ =============================================================================== -c90e4fa9288f1fcb3c5c273e38250e5e +5e3c967fc04dd3bab4c2d876e227f62c This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/data_modeling/data_models.py b/cognite/client/_sync_api/data_modeling/data_models.py index 7fb1e94416..dfe4071aa0 100644 --- a/cognite/client/_sync_api/data_modeling/data_models.py +++ b/cognite/client/_sync_api/data_modeling/data_models.py @@ -1,6 +1,6 @@ """ =============================================================================== -c0954d6bae1380177776758fc555f3c8 +059bf0313b1b78487b9d7972593f9de2 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/data_modeling/graphql.py b/cognite/client/_sync_api/data_modeling/graphql.py index 6ead37f2c3..b4eefea91c 100644 --- a/cognite/client/_sync_api/data_modeling/graphql.py +++ b/cognite/client/_sync_api/data_modeling/graphql.py @@ -1,6 +1,6 @@ """ =============================================================================== -4c797ab98ba8663bd1d57f352855c2ef +8ac435c2d091d6377fe3bca5728611de This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/data_modeling/instances.py b/cognite/client/_sync_api/data_modeling/instances.py index d02b5eb574..471be77029 100644 --- a/cognite/client/_sync_api/data_modeling/instances.py +++ b/cognite/client/_sync_api/data_modeling/instances.py @@ -1,6 +1,6 @@ """ =============================================================================== -1a6f5bf3b92a38c80ab64f4a1d9f01c1 +77ddb197a6a73314c704dafacbe56215 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ @@ -481,7 +481,7 @@ def inspect( involved_containers: InvolvedContainers | None = None, ) -> InstanceInspectResults: """ - `Reverse lookup for instances. `_ + `Reverse lookup for instances. `_ This method will return the involved views and containers for the given nodes and edges. @@ -605,6 +605,7 @@ def apply( auto_create_direct_relations (bool): Whether to create missing direct relation targets when ingesting. skip_on_version_conflict (bool): If existingVersion is specified on any of the nodes/edges in the input, the default behaviour is that the entire ingestion will fail when version conflicts occur. If skipOnVersionConflict is set to true, items with version conflicts will be skipped instead. If no version is specified for nodes/edges, it will do the writing directly. replace (bool): How do we behave when a property value exists? Do we replace all matching and existing values with the supplied values (true)? Or should we merge in new values for properties together with the existing values (false)? Note: This setting applies for all nodes or edges specified in the ingestion call. + Returns: InstancesApplyResult: Created instance(s) @@ -803,7 +804,7 @@ def search( operator: Literal["AND", "OR"] = "AND", ) -> NodeList[T_Node] | EdgeList[T_Edge]: """ - `Search instances `_ + `Search instances `_ Args: view (ViewId): View to search in. @@ -929,7 +930,7 @@ def aggregate( limit: int | None = DEFAULT_LIMIT_READ, ) -> AggregatedNumberedValue | list[AggregatedNumberedValue] | InstanceAggregationResultList: """ - `Aggregate data across nodes/edges `_ + `Aggregate data across nodes/edges `_ Args: view (ViewId): View to aggregate over. @@ -1018,7 +1019,7 @@ def histogram( limit: int = DEFAULT_LIMIT_READ, ) -> HistogramValue | list[HistogramValue]: """ - `Produces histograms for nodes/edges `_ + `Produces histograms for nodes/edges `_ Args: view (ViewId): View to to aggregate over. @@ -1063,7 +1064,7 @@ def histogram( def query(self, query: Query, include_typing: bool = False, debug: DebugParameters | None = None) -> QueryResult: """ - `Advanced query interface for nodes/edges. `_ + `Advanced query interface for nodes/edges. `_ The Data Modelling API exposes an advanced query interface. The query interface supports parameterization, recursive edge traversal, chaining of result sets, and granular property selection. @@ -1158,7 +1159,7 @@ def query(self, query: Query, include_typing: bool = False, debug: DebugParamete def sync(self, query: QuerySync, include_typing: bool = False, debug: DebugParameters | None = None) -> QueryResult: """ - `Subscription to changes for nodes/edges. `_ + `Subscription to changes for nodes/edges. `_ Subscribe to changes for nodes and edges in a project, matching a supplied filter. diff --git a/cognite/client/_sync_api/data_modeling/space_statistics.py b/cognite/client/_sync_api/data_modeling/space_statistics.py index 88351f2721..f182cf5561 100644 --- a/cognite/client/_sync_api/data_modeling/space_statistics.py +++ b/cognite/client/_sync_api/data_modeling/space_statistics.py @@ -1,6 +1,6 @@ """ =============================================================================== -05d5d71f1fec9f95dd16fc44e599c4a3 +533d33cb32bbf0b0561e66c3e06c3b63 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/data_modeling/spaces.py b/cognite/client/_sync_api/data_modeling/spaces.py index aa3c3f092d..3817b0b7c5 100644 --- a/cognite/client/_sync_api/data_modeling/spaces.py +++ b/cognite/client/_sync_api/data_modeling/spaces.py @@ -1,6 +1,6 @@ """ =============================================================================== -00951520dd16f01e10744a33fb2dba86 +e7bcba053c734addd5c227721c494fbb This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/data_modeling/views.py b/cognite/client/_sync_api/data_modeling/views.py index 12e9269e6b..81f9c337f9 100644 --- a/cognite/client/_sync_api/data_modeling/views.py +++ b/cognite/client/_sync_api/data_modeling/views.py @@ -1,6 +1,6 @@ """ =============================================================================== -0c976425b581eb02458eccf3d09054bb +3b362be0b839452958bd6fa808ea60ae This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/data_sets.py b/cognite/client/_sync_api/data_sets.py index ae8a88f2ff..e294e78ae5 100644 --- a/cognite/client/_sync_api/data_sets.py +++ b/cognite/client/_sync_api/data_sets.py @@ -1,6 +1,6 @@ """ =============================================================================== -9eb0fa8e6a0fa0bdab94a894c39f081b +d6290ad992aa92d45348615e74088435 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/datapoints.py b/cognite/client/_sync_api/datapoints.py index 45d7534589..c569fd31b2 100644 --- a/cognite/client/_sync_api/datapoints.py +++ b/cognite/client/_sync_api/datapoints.py @@ -1,6 +1,6 @@ """ =============================================================================== -c12d4b792acc40a524035e96f591caa6 +23e5743beeccf6620ee13a82ae8b2e16 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/datapoints_subscriptions.py b/cognite/client/_sync_api/datapoints_subscriptions.py index 09d2103e76..bf1ba4f8bd 100644 --- a/cognite/client/_sync_api/datapoints_subscriptions.py +++ b/cognite/client/_sync_api/datapoints_subscriptions.py @@ -1,6 +1,6 @@ """ =============================================================================== -85e289f5eaf4fab3b555c4c777a0fb48 +1f89e9a889e39eb80722528f530f6678 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/diagrams.py b/cognite/client/_sync_api/diagrams.py index 525ccd1af9..49a0dd8ea2 100644 --- a/cognite/client/_sync_api/diagrams.py +++ b/cognite/client/_sync_api/diagrams.py @@ -1,6 +1,6 @@ """ =============================================================================== -4505d0c9269fbe813d8294bf729185ea +91d19c1cf73511fffb16ad63b08c027d This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/document_preview.py b/cognite/client/_sync_api/document_preview.py index 3294dc2f9e..49d8c3d2e7 100644 --- a/cognite/client/_sync_api/document_preview.py +++ b/cognite/client/_sync_api/document_preview.py @@ -1,6 +1,6 @@ """ =============================================================================== -44a68cea70b8d3050b8d645d272a0a1d +f999f64709f94d34e77af1c36a037561 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/documents.py b/cognite/client/_sync_api/documents.py index 43c812f2a4..9de29cc32b 100644 --- a/cognite/client/_sync_api/documents.py +++ b/cognite/client/_sync_api/documents.py @@ -1,6 +1,6 @@ """ =============================================================================== -80d047bf302bcef2d84542d426c1f78d +3ec6c9ff3cd20cbefde273d76514a0b0 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/entity_matching.py b/cognite/client/_sync_api/entity_matching.py index 4cb7a99327..5724279aaa 100644 --- a/cognite/client/_sync_api/entity_matching.py +++ b/cognite/client/_sync_api/entity_matching.py @@ -1,6 +1,6 @@ """ =============================================================================== -b2da14e5521c45294cd1a9750875a8ce +2d6e1ebcc76109dbd96fd3269d590f67 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/events.py b/cognite/client/_sync_api/events.py index d700cb52a1..23943ced09 100644 --- a/cognite/client/_sync_api/events.py +++ b/cognite/client/_sync_api/events.py @@ -1,6 +1,6 @@ """ =============================================================================== -56d3a886b113ba35e8c796fe69e7a7b9 +edbf16b9fd90eaf16868adde518851eb This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/extractionpipelines/__init__.py b/cognite/client/_sync_api/extractionpipelines/__init__.py index 0e9c523a31..18bde60036 100644 --- a/cognite/client/_sync_api/extractionpipelines/__init__.py +++ b/cognite/client/_sync_api/extractionpipelines/__init__.py @@ -1,6 +1,6 @@ """ =============================================================================== -990fd1dcf9185a7f006b22b1245e506e +a137ea2563d43bc87d9193fab4a98294 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/extractionpipelines/configs.py b/cognite/client/_sync_api/extractionpipelines/configs.py index 749182560b..7b23da904a 100644 --- a/cognite/client/_sync_api/extractionpipelines/configs.py +++ b/cognite/client/_sync_api/extractionpipelines/configs.py @@ -1,6 +1,6 @@ """ =============================================================================== -3f683d6b90598c40be474b7f0a5f045d +6aea66afa91ba4af7b9d6663e4e72411 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/extractionpipelines/runs.py b/cognite/client/_sync_api/extractionpipelines/runs.py index 9f0ecdfb7e..40fa530209 100644 --- a/cognite/client/_sync_api/extractionpipelines/runs.py +++ b/cognite/client/_sync_api/extractionpipelines/runs.py @@ -1,6 +1,6 @@ """ =============================================================================== -d399a8a45c39407e7217371176777da7 +87c5631796b06cbb4946c5e196e0b698 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/files.py b/cognite/client/_sync_api/files.py index 6da9ad130f..71f56c860e 100644 --- a/cognite/client/_sync_api/files.py +++ b/cognite/client/_sync_api/files.py @@ -1,6 +1,6 @@ """ =============================================================================== -66074a72c742cc8bdcd3dbdfc5dc64a6 +03cd8a67df9d7f34c3d962122233d689 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/functions/__init__.py b/cognite/client/_sync_api/functions/__init__.py index 8176cba809..fbc7862247 100644 --- a/cognite/client/_sync_api/functions/__init__.py +++ b/cognite/client/_sync_api/functions/__init__.py @@ -1,6 +1,6 @@ """ =============================================================================== -2ef5734f88e1142ea7c9e90a631fd14d +e7f4764857e771bb7ae576073fda06ad This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/functions/schedules.py b/cognite/client/_sync_api/functions/schedules.py index dc5bfcc309..6885155107 100644 --- a/cognite/client/_sync_api/functions/schedules.py +++ b/cognite/client/_sync_api/functions/schedules.py @@ -1,6 +1,6 @@ """ =============================================================================== -125e07108e5c3912a4bc1207f66165b4 +e02328a28dd98bb623ba5f9f7d6392f1 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/geospatial.py b/cognite/client/_sync_api/geospatial.py index 2a402b12e3..faa2b4d70a 100644 --- a/cognite/client/_sync_api/geospatial.py +++ b/cognite/client/_sync_api/geospatial.py @@ -1,6 +1,6 @@ """ =============================================================================== -ba8724988fe9f1745b82c296e14903e8 +d1c6c58669aed07e457031a53ba3a9f5 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/hosted_extractors/destinations.py b/cognite/client/_sync_api/hosted_extractors/destinations.py index d729e231b7..65165addb4 100644 --- a/cognite/client/_sync_api/hosted_extractors/destinations.py +++ b/cognite/client/_sync_api/hosted_extractors/destinations.py @@ -1,6 +1,6 @@ """ =============================================================================== -895b73fbf30659992b85ce9503f7339f +28f7a5910b107d7d73b36d002ac8fde3 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/hosted_extractors/jobs.py b/cognite/client/_sync_api/hosted_extractors/jobs.py index 642b99533b..13395bf2fb 100644 --- a/cognite/client/_sync_api/hosted_extractors/jobs.py +++ b/cognite/client/_sync_api/hosted_extractors/jobs.py @@ -1,6 +1,6 @@ """ =============================================================================== -bd17aab24c1acbcf37ae90452f8d16b4 +d312d8c2fd7c416d293c1d77ad653809 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/hosted_extractors/mappings.py b/cognite/client/_sync_api/hosted_extractors/mappings.py index c3bcdfa4dc..399bf21b86 100644 --- a/cognite/client/_sync_api/hosted_extractors/mappings.py +++ b/cognite/client/_sync_api/hosted_extractors/mappings.py @@ -1,6 +1,6 @@ """ =============================================================================== -d93326405938df60470510da7470796c +7284c8ddb0de35ee8b871e9aae3bb31e This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/hosted_extractors/sources.py b/cognite/client/_sync_api/hosted_extractors/sources.py index 527bd6d472..410b28971d 100644 --- a/cognite/client/_sync_api/hosted_extractors/sources.py +++ b/cognite/client/_sync_api/hosted_extractors/sources.py @@ -1,6 +1,6 @@ """ =============================================================================== -57229c9ea704a67803cbabb095076fd7 +bc7f7007847267d777980381810dd27b This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/iam/__init__.py b/cognite/client/_sync_api/iam/__init__.py index 763e82fd94..d9cb6a769c 100644 --- a/cognite/client/_sync_api/iam/__init__.py +++ b/cognite/client/_sync_api/iam/__init__.py @@ -1,6 +1,6 @@ """ =============================================================================== -dee7369c5fe919ffd146a7c16845acea +f32424b35163317d66e8fca6f331c853 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/iam/groups.py b/cognite/client/_sync_api/iam/groups.py index 0464705d02..da041668c9 100644 --- a/cognite/client/_sync_api/iam/groups.py +++ b/cognite/client/_sync_api/iam/groups.py @@ -1,6 +1,6 @@ """ =============================================================================== -761d85b5a471cbe3058049d6cf816fb2 +4a0a07131386c8ecbd12af4fe10decdf This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/labels.py b/cognite/client/_sync_api/labels.py index 96d2badfb2..2ae42bc9fd 100644 --- a/cognite/client/_sync_api/labels.py +++ b/cognite/client/_sync_api/labels.py @@ -1,6 +1,6 @@ """ =============================================================================== -765bcd562409805c3100a5a77572f779 +eb1faa194c1dca8c8c3162a77f4117bd This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/postgres_gateway/tables.py b/cognite/client/_sync_api/postgres_gateway/tables.py index dd7a0f9671..195a60b58d 100644 --- a/cognite/client/_sync_api/postgres_gateway/tables.py +++ b/cognite/client/_sync_api/postgres_gateway/tables.py @@ -1,6 +1,6 @@ """ =============================================================================== -789d58776aa258529e2d0c9453d9e029 +7126db36cdba09e20f2eb5a35e329670 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/postgres_gateway/users.py b/cognite/client/_sync_api/postgres_gateway/users.py index fb02976402..fb39f273d0 100644 --- a/cognite/client/_sync_api/postgres_gateway/users.py +++ b/cognite/client/_sync_api/postgres_gateway/users.py @@ -1,6 +1,6 @@ """ =============================================================================== -8e339ffece20e9f0685104f8b625f982 +e35accda8afad8bee55794434a18f65c This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/raw/databases.py b/cognite/client/_sync_api/raw/databases.py index d5e0188a66..92dc2f7dda 100644 --- a/cognite/client/_sync_api/raw/databases.py +++ b/cognite/client/_sync_api/raw/databases.py @@ -1,6 +1,6 @@ """ =============================================================================== -d71668f67fe505fcc40cf96d04515217 +d108ba3a9714d425527ed7e4bbab9413 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/raw/rows.py b/cognite/client/_sync_api/raw/rows.py index f40c88eb59..b2dedb0809 100644 --- a/cognite/client/_sync_api/raw/rows.py +++ b/cognite/client/_sync_api/raw/rows.py @@ -1,6 +1,6 @@ """ =============================================================================== -0989d001b864f38f2765c784ab0b6bbc +f4e1098248aa0435df188100512548d0 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/raw/tables.py b/cognite/client/_sync_api/raw/tables.py index a491eeff5a..be0d6d9af4 100644 --- a/cognite/client/_sync_api/raw/tables.py +++ b/cognite/client/_sync_api/raw/tables.py @@ -1,6 +1,6 @@ """ =============================================================================== -d534ac15730b4ed878bf7f7c57078053 +d1feeb34081c9b8719db7769e1dc00a7 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/relationships.py b/cognite/client/_sync_api/relationships.py index 18949c9348..a647090728 100644 --- a/cognite/client/_sync_api/relationships.py +++ b/cognite/client/_sync_api/relationships.py @@ -1,6 +1,6 @@ """ =============================================================================== -dc8a46cd5a243f74255baac0d3c5a05c +d31286ebf278cd9c14c11d678adddd33 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/sequence_data.py b/cognite/client/_sync_api/sequence_data.py index 5977dbcf6b..4ac867aefa 100644 --- a/cognite/client/_sync_api/sequence_data.py +++ b/cognite/client/_sync_api/sequence_data.py @@ -1,6 +1,6 @@ """ =============================================================================== -05468959ae43bae014e192eed2dff0fc +24d6447eb14621ef444322baea614541 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/sequences.py b/cognite/client/_sync_api/sequences.py index 0ed9c4b5aa..819240415f 100644 --- a/cognite/client/_sync_api/sequences.py +++ b/cognite/client/_sync_api/sequences.py @@ -1,6 +1,6 @@ """ =============================================================================== -cc89586f372d9253c2922ea011bb2271 +8fd9acfa00bfb4f96ba621c65e7fa11f This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/simulators/integrations.py b/cognite/client/_sync_api/simulators/integrations.py index 51b1447aef..1b6f279edf 100644 --- a/cognite/client/_sync_api/simulators/integrations.py +++ b/cognite/client/_sync_api/simulators/integrations.py @@ -1,6 +1,6 @@ """ =============================================================================== -5a294ddb1e46a72af027796934d0113d +cc66cced91c72607a9a48412b697fc97 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/simulators/models.py b/cognite/client/_sync_api/simulators/models.py index 7a7e24137f..2bf8c38e95 100644 --- a/cognite/client/_sync_api/simulators/models.py +++ b/cognite/client/_sync_api/simulators/models.py @@ -1,6 +1,6 @@ """ =============================================================================== -daa3274e810f251e36271b95a35470d1 +4f5f358c779dd350123fd61c39bfbfb8 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/simulators/models_revisions.py b/cognite/client/_sync_api/simulators/models_revisions.py index ed6c40fc3e..0a979f902c 100644 --- a/cognite/client/_sync_api/simulators/models_revisions.py +++ b/cognite/client/_sync_api/simulators/models_revisions.py @@ -1,6 +1,6 @@ """ =============================================================================== -6e15873ee25a04f1096a0990d9114164 +fb7d457799eb07aa51d4dd24a2224b5e This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/simulators/routine_revisions.py b/cognite/client/_sync_api/simulators/routine_revisions.py index d5b8ef7e6b..19bb622f4f 100644 --- a/cognite/client/_sync_api/simulators/routine_revisions.py +++ b/cognite/client/_sync_api/simulators/routine_revisions.py @@ -1,6 +1,6 @@ """ =============================================================================== -cc8143e90a00dbc0d1a9bde49d575f7f +a4f7d5db770f623f0487f34ba9a253b4 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/simulators/routines.py b/cognite/client/_sync_api/simulators/routines.py index 4d4814b7df..c95c47beb8 100644 --- a/cognite/client/_sync_api/simulators/routines.py +++ b/cognite/client/_sync_api/simulators/routines.py @@ -1,6 +1,6 @@ """ =============================================================================== -ab338dba609a32a293cb2ec8821708c7 +17670bceb1994820354843fd55b8e7a9 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/simulators/runs.py b/cognite/client/_sync_api/simulators/runs.py index 2688735302..ec12e700dd 100644 --- a/cognite/client/_sync_api/simulators/runs.py +++ b/cognite/client/_sync_api/simulators/runs.py @@ -1,6 +1,6 @@ """ =============================================================================== -5249b52d0fdba5befd01c862f3e7ce5d +3fb2bb1e260073e2d54317794dab4d4d This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/synthetic_time_series.py b/cognite/client/_sync_api/synthetic_time_series.py index a3ac727512..8a71295c3f 100644 --- a/cognite/client/_sync_api/synthetic_time_series.py +++ b/cognite/client/_sync_api/synthetic_time_series.py @@ -1,6 +1,6 @@ """ =============================================================================== -ab726051b4211c47ec54ff723645aee3 +33d39ce5b3cd74e806a3d511931e65f1 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/three_d/asset_mapping.py b/cognite/client/_sync_api/three_d/asset_mapping.py index a0c1359462..5e3556aff7 100644 --- a/cognite/client/_sync_api/three_d/asset_mapping.py +++ b/cognite/client/_sync_api/three_d/asset_mapping.py @@ -1,6 +1,6 @@ """ =============================================================================== -42931410f3fb2cf143cddcd4cd3075dc +ac85717720c349aa2b707d51176c31a7 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/three_d/models.py b/cognite/client/_sync_api/three_d/models.py index 1747f7ee12..251cd4a6db 100644 --- a/cognite/client/_sync_api/three_d/models.py +++ b/cognite/client/_sync_api/three_d/models.py @@ -1,6 +1,6 @@ """ =============================================================================== -c0fdd9917d4201cf971771159e7740c9 +bbf19ca65eaac5dabe7ab700b5da116c This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/three_d/revisions.py b/cognite/client/_sync_api/three_d/revisions.py index 0891bb17a2..94d610a863 100644 --- a/cognite/client/_sync_api/three_d/revisions.py +++ b/cognite/client/_sync_api/three_d/revisions.py @@ -1,6 +1,6 @@ """ =============================================================================== -900ad0523c4b914c4a8e70d0faf3b679 +94dd32d18e1b4434028a397ad805394e This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/time_series.py b/cognite/client/_sync_api/time_series.py index c0c35c2c7a..602855f17e 100644 --- a/cognite/client/_sync_api/time_series.py +++ b/cognite/client/_sync_api/time_series.py @@ -1,6 +1,6 @@ """ =============================================================================== -50c24126e5e02623a6ba1aca2667303f +0ac4c466f82103d99417b4bfa55652b3 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/transformations/__init__.py b/cognite/client/_sync_api/transformations/__init__.py index d25364fdf1..ebafd18f6e 100644 --- a/cognite/client/_sync_api/transformations/__init__.py +++ b/cognite/client/_sync_api/transformations/__init__.py @@ -1,6 +1,6 @@ """ =============================================================================== -1a494e5ef4495baf6939256abff06c0f +c4bd2c89763bb5b23ad5f34db1671b96 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/transformations/notifications.py b/cognite/client/_sync_api/transformations/notifications.py index 2e1b10f787..f1124995c3 100644 --- a/cognite/client/_sync_api/transformations/notifications.py +++ b/cognite/client/_sync_api/transformations/notifications.py @@ -1,6 +1,6 @@ """ =============================================================================== -573a554ba19bfee47533a4650862530e +e0f66a6e5f58b8b52270420ca7ab3d38 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/transformations/schedules.py b/cognite/client/_sync_api/transformations/schedules.py index ed8e1e0bb2..b965462b0d 100644 --- a/cognite/client/_sync_api/transformations/schedules.py +++ b/cognite/client/_sync_api/transformations/schedules.py @@ -1,6 +1,6 @@ """ =============================================================================== -e0f9860956a1f01ae406c4ed41f27818 +9acb6f16c3d6ea331c279305cedaf162 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/units.py b/cognite/client/_sync_api/units.py index cbb48e319b..63bcdf446b 100644 --- a/cognite/client/_sync_api/units.py +++ b/cognite/client/_sync_api/units.py @@ -1,6 +1,6 @@ """ =============================================================================== -dbc2ed4a0d0352b8e5b0712b0e53cd61 +79aaab7ac35c746786d31b7b7fcbc43c This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/vision.py b/cognite/client/_sync_api/vision.py index 67c91420dd..dd5da1dfbc 100644 --- a/cognite/client/_sync_api/vision.py +++ b/cognite/client/_sync_api/vision.py @@ -1,6 +1,6 @@ """ =============================================================================== -8ad053d3d1c03509fe940908997aa93f +ef3951b05d4235a59e1c676636514dfa This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/workflows/executions.py b/cognite/client/_sync_api/workflows/executions.py index 218ad0028e..82f4c27500 100644 --- a/cognite/client/_sync_api/workflows/executions.py +++ b/cognite/client/_sync_api/workflows/executions.py @@ -1,6 +1,6 @@ """ =============================================================================== -395576730bb3f216eef02cbe72b628ea +9186d73f1b2531afe7fcb861ec953adf This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/workflows/tasks.py b/cognite/client/_sync_api/workflows/tasks.py index bc8dad4fb9..c3545ac159 100644 --- a/cognite/client/_sync_api/workflows/tasks.py +++ b/cognite/client/_sync_api/workflows/tasks.py @@ -1,6 +1,6 @@ """ =============================================================================== -00f698c970d43d29fc5df777446fe4f3 +2fcd5b66981917f57fcec085afc04f32 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/workflows/triggers.py b/cognite/client/_sync_api/workflows/triggers.py index 9167c449b6..3d9515084b 100644 --- a/cognite/client/_sync_api/workflows/triggers.py +++ b/cognite/client/_sync_api/workflows/triggers.py @@ -1,6 +1,6 @@ """ =============================================================================== -a808b1b2149cbf64dad167875d606403 +5b44b9267cff1314fd65f0fb32ed0170 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """ diff --git a/cognite/client/_sync_api/workflows/versions.py b/cognite/client/_sync_api/workflows/versions.py index 8de5b97bc6..fa808a932c 100644 --- a/cognite/client/_sync_api/workflows/versions.py +++ b/cognite/client/_sync_api/workflows/versions.py @@ -1,6 +1,6 @@ """ =============================================================================== -362d76a56f7ddf064d938ced60fd759e +e7b1d109b027b1cc8c22065d4ac11838 This file is auto-generated from the Async API modules, - do not edit manually! =============================================================================== """