Streamlined API Reference
Last update: 16.07.2025The classes and functions that form the Streamlined API are grouped by database element, to help you find what you need:
Session level
Session
class Session(service_layer_url, user_name=None, password=None, domain=None, autologon=None, timeout=300000, existing_session=None, oidc=False, auth_token=None, refresh_token=None, use_stored_token=False, store_password=False, max_retries=0, backend_configuration=BackendServiceSelection(search=<BackendType.SOAP: 0>, data_export=<BackendType.SOAP: 0>, data_import=<BackendType.SOAP: 0>, browse=<BackendType.SOAP: 0>, engineering_data=<BackendType.SOAP: 0>))
Represents a Granta MI Session. Allows the MI Scripting Toolkit to make calls to the Service Layer, and provides access to and search functions for available databases.
__init__(service_layer_url, user_name=None, password=None, domain=None, autologon=None, timeout=300000, existing_session=None, oidc=False, auth_token=None, refresh_token=None, use_stored_token=False, store_password=False, max_retries=0, backend_configuration=BackendServiceSelection(search=<BackendType.SOAP: 0>, data_export=<BackendType.SOAP: 0>, data_import=<BackendType.SOAP: 0>, browse=<BackendType.SOAP: 0>, engineering_data=<BackendType.SOAP: 0>))
- Parameters:
- service_layer_url – str
- user_name – str
- password – str
- domain – str
- autologon – bool
- timeout – int (Maximum time to wait for a response, in milliseconds)
- existing_session – Foundation API
GRANTA_MIScriptingToolkit.GRANTA_MISessionclass- oidc – bool (Contact Ansys Technical Support for Granta MI OIDC configuration and setup documentation)
- auth_token – str
- refresh_token – str
- use_stored_token – bool
- store_password – bool (Default value False. Set to True when password is given and needs to be saved for the session’s duration, for example when parallelisation is required.)
- max_retries – int (Default value 0. Maximum number of times to retry requests sent to the Service Layer.)
- Returns: None
NOTE
If MI Scripting Toolkit has been installed on the same server machine as Granta MI, then the Granta MI server name must be specified in full in the url parameter. If you use ‘localhost’ or a loopback address, MI Scripting Toolkit will be unable to use the specified user account to connect to Granta MI.
update(records, update_attributes=True, update_links=False, refresh_attributes=True, include_binary_data_in_refresh=False, notes=None, release_notes=None)
Pushes any changes in the specified records (including adding newly-created records) to the server.
Returns a list of successfully imported Record objects. If refresh_attributes
set to True, the imported records’ attributes are exported after the update is complete.
If include_binary_data_in_refresh is set to False (default), the export will not fetch the binary data
representing the request File and Picture attributes and will instead export URLs (see the
BinaryType.url documentation for more information on how to use the URL to access the data). This
setting is recommended for large files and pictures, or if the binary data itself is not required.
To summarize how the file and picture data can be accessed:
include_binary_data_in_refresh = False(default): TheBinaryType.urlproperty is populated.include_binary_data_in_refresh = True: TheBinaryType.binary_dataproperty, andAttributeFile.save()andAttributePicture.save()methods are all available to access and save the binary data. TheBinaryType.urlproperty is empty and returnsNone.
WARNING
If include_binary_data_in_refresh is set to False, the binary_data property and save() method are
both still available for backwards compatibility. However, they will download the data from Granta MI on
demand for each attribute value. A warning will be generated each time this occurs, but may only occur once
due to the Python warning configuration settings.
This behavior is likely to have a significant performance impact, and so it is recommended that if access to
the binary data is required without a subsequent HTTP GET request, you should specify
include_binary_data_in_refresh = True.
On-demand access to attribute values without using Table.bulk_fetch() is unaffected.
- Parameters:
- records – List[
Record] - update_attributes – bool (default value of True)
- update_links – bool (default value of False)
- refresh_attributes – bool (default value of True)
- include_binary_data_in_refresh – bool (default value of False)
- notes – str (default value of None). Revision notes for the update. Applies to all records in the update.
- release_notes – str (default value of None). Version release notes for the update. Applies to all records flagged for release in the update.
- records – List[
- Returns:
List[
Record]
update_links(records)
Pushes any changes in the links of the specified records (including newly-created records) to the server.
Returns a list of successfully modified Record objects. All source and target records must be exported
to/from the server before being linked.
spawn_session()
Creates a new Foundation API GRANTA_MIScriptingToolkit.GRANTA_MISession object using the credentials
of the current Session.
If the session was created with manual credentials, then this method will only succeed if store_password
was set to True. Otherwise, this method will return None.
- Returns:
Foundation API
GRANTA_MIScriptingToolkit.GRANTA_MISessionclass
WARNING
Calling this method from a Session object that was constructed with manual credentials and
without setting store_password to True is deprecated and will raise an exception in a
future release.
property viewer_base_url
MI Viewer URL associated with the Service Layer.
- Returns: str
can_connect()
Checks whether credentials have been provided to the server.
- Returns: bool
assert_can_run_parallelised()
Throws if a task cannot run in parallel mode with current session.
connect(spawn_new_connection=True)
Returns a Foundation API GRANTA_MIScriptingToolkit.GRANTA_MISession object using the current
Session’s credentials.
- Parameters: spawn_new_connection – bool (default value True)
- Returns:
Foundation API
GRANTA_MIScriptingToolkit.GRANTA_MISessionclass
persist_oidc_token()
Stores a refresh token in the credential manager for your system for unattended later use. The keyring
package uses system-managed storage, and supports the following credential managers:
-
Windows Credential Manager
-
macOS Keychain
-
Freedesktop Secret Service
-
KDE4 and KDE5 KWallet
-
Returns: None
refetch_dbs()
Fetches the list of databases from the server. Makes a Service Layer call.
- Returns: None
property dbs
List of databases on the server.
- Returns:
List[
Database]
property dbs_by_key
Dict of databases on the server, keyed by database key
- Returns:
Dict[str,
Database]
property dbs_by_guid
Dict of databases on the server, keyed by database GUID
- Returns:
Dict[str,
Database]
get_db(name=None, db_key=None, guid=None, version_guid=None)
Returns the database matching the specified criteria. Provide at least one of:
- Database name:
name- Database key:
db_key- Database GUID:
guid- Database Version GUID:
version_guid
Raises a KeyError if multiple databases are found for the same criteria. Raises a KeyError if no databases are found matching the provided criteria.
- Parameters:
- name – str
- db_key – str
- guid – str
- version_guid – str
- Returns:
Databaseobject
search_for_records_by_name(name)
Searches by record name over all databases
(uses Database.search_for_records_by_name()).
Makes a Service Layer call for each table in each database.
- Parameters: name – str
- Returns:
List[
Record]
search_for_records_by_text(text)
Performs a simple text search over all databases
(uses Database.search_for_records_by_text()).
Makes a Service Layer call for each table in each database.
- Parameters: text – str
- Returns:
List[
Record]
records_from_string(text, use_strict_version=True)
Generates Record objects from a string in MI clipboard format (version 12 or higher).
NOTE
Required string format is .tsv with column headers RecordHistoryGuid, RecordGuid, Table, DatabaseKey and RecordFullName.
NOTE
In MI Viewer, a field name may be prefixed by an asterisk to denote a default Match
Column. This functionality is not supported in the Scripting Toolkit. Either the
RecordHistoryGuid (if use_strict_mode = False) or RecordGuid (if
use_strict_mode = True) will be used to identify the record.
- Parameters:
- text – str
- use_strict_version – bool (default value of
True) - IfTrue, return only the specified version of the record (if you do not have permission, the item will beNone). IfFalse, return the latest visible version of the record.
- Returns:
List[
Record]
get_record_by_id(db_key, hguid=None, vguid=None, history_identity=None, version_number=None)
Returns the record with the specified ID from the database specified by db_key. This
method resolves records with the following (sets of) references in priority order:
vguid(Record GUID - uniquely identifies specific version of record)history_identity(Record history identity - uniquely identifies record only), and optionallyversion_number(Record version number)hguid(Record History GUID - uniquely identifies record only)
If vguid or version_number are not provided for version controlled records, this method will
return the latest available version of the record available to the user. The latest available version
is dependent on the user’s Granta MI permissions.
- Parameters:
- db_key – str
- hguid – str (Record History GUID, uniquely identifies record)
- vguid – str (Record GUID, uniquely identifies record version)
- history_identity – int (Record history identity)
- version_number – int (Record version number)
- Returns:
Recordobject
get_records_by_ids(record_identifiers)
Returns a Record object for each identifier provided. The returned list of records
will have the same number of elements as the provided list of identifiers. If no record corresponds
to that identifier then the corresponding item in the returned list will be None.
Each element in the record_identifiers parameter should be a dictionary with the db_key entry.
Additionally, it must contain one or more of the following (sets of) references in priority order:
vguid(Record GUID - uniquely identifies specific version of record)history_identity(Record history identity - uniquely identifies record only), and optionallyversion_number(Record version number)hguid(Record History GUID - uniquely identifies record only)
If vguid or version_number are not provided for version controlled records, this method will
return the latest available version of the record available to the user. The latest available version
is dependent on the user’s Granta MI permissions.
- Parameters: record_identifiers – Sequence[Dict[str, Union[str, int]]]
- Returns:
List[
Record]
bulk_fetch_release_states(records, batch_size=100, parallelise=False, max_num_threads=6)
Fetches and populates the release states of the specified Record objects.
- Parameters:
- records – List[
Record] - batch_size – int (default value of 100)
- parallelise – bool
- max_num_threads – int (default value of 6)
- records – List[
- Returns: None
bulk_delete_or_withdraw_records(records, batch_size=100, parallelise=False, max_num_threads=6, update_release_states=False, withdrawal_notes=None)
Deletes records from the server (or withdraws them, if in a version-controlled table). Record release states can also be updated using this method.
- Parameters:
- records – List[
Record] - batch_size – int (default value of 100)
- parallelise – bool
- max_num_threads – int (default value of 6)
- update_release_states – bool
- withdrawal_notes – Optional[str]
- records – List[
- Returns: None
AttributeFetcher
class AttributeFetcher(table, batch_size=100, attributes=None, records=None, max_parallel_threads=6, include_binary_data=False)
Bulk exporter for record data. Fetches data values for all named AttributeDefinition and
PseudoAttributeDefinition objects from the specified Record objects and Table.
Set attributes to None to export all record data.
A class method executes the data export, allowing the AttributeFetcher to be edited post-creation.
__init__(table, batch_size=100, attributes=None, records=None, max_parallel_threads=6, include_binary_data=False)
- Parameters:
- table –
Tableobject - batch_size – int (default value of 100)
- attributes – List[Union[
AttributeDefinition,PseudoAttributeDefinition, str]] - records – List[
Record] - max_parallel_threads – int (default value of 6)
- include_binary_data – bool (default value of False)
- table –
- Returns: None
property records
List of records to be fetched (exported).
- Returns:
List[
Record]
property attribute_list
List of attributes for which data will be fetched (exported).
- Returns:
List[Union[
AttributeDefinition,PseudoAttributeDefinition]]
fetch_attribute_data(parallelise=False)
Fetch the attribute data for the provided records and attributes, and populate the corresponding
AttributeValue objects for each record.
- Parameters: parallelise – bool
- Returns: None
AssociatedRecordFetcher
class AssociatedRecordFetcher(table, records, target_table, link_direction='Both', attribute_path=None, batch_size=100)
Bulk fetcher for associated records. Fetches all Record objects via association chains from the specified
Record objects in the target Table. Provides means to choose the direction that association chains
are followed, and to specify a list of tabular attributes which are chained together.
This operation performs no subset filtering.
A class method executes the fetch, allowing the AssociatedRecordFetcher to be edited post-creation.
__init__(table, records, target_table, link_direction='Both', attribute_path=None, batch_size=100)
- Parameters:
- table –
Table - records – List[
Record] - target_table –
Table - link_direction – str (
Both,Forward,Reverse) - attribute_path – List[
AttributeDefinition] - batch_size – int (default value of 100)
- table –
- Returns: None
fetch_associated_records(parallelise=False, max_parallel_threads=6)
Fetch the associated records in the specified Table from the specified Record objects. Return a
list of dictionaries with source_record and associated_records fields for each provided
Record.
This operation performs no subset filtering.
LinkFetcher
class LinkFetcher(table, batch_size=100, records=None, link_groups=None, filter_subsets=True)
Bulk record link fetcher (exporter). Fetches and populates record link groups for the specified Record
objects in the specified Table. Set link_groups to None to fetch all record link groups.
Set filter_subsets to True to return records that are in the default subsets of the target table.
Set it to False to search with no filtering by subset.
__init__(table, batch_size=100, records=None, link_groups=None, filter_subsets=True)
- Parameters:
- Returns: None
property link_groups
List of link groups to export.
- Returns: List[str]
property records
List of records to fetch link groups for.
- Returns:
List[
Record]
fetch_linked_records(parallelise=False, max_parallel_threads=6)
Perform the bulk fetch (export). Batches Service Layer calls into efficient blocks, then populates
Record object pseudo-attributes.
- Parameters:
- parallelise – bool
- max_parallel_threads – int (default value of 6)
- Returns: None
ReleaseStateFetcher
class ReleaseStateFetcher(session, records, batch_size=100, max_parallel_threads=6)
Allows record release states to be fetched from the server in bulk.
The list of Record objects, batch size, and number of threads in parallel can be edited post-creation.
A class method fetches the release states and populates the relevant Record properties.
__init__(session, records, batch_size=100, max_parallel_threads=6)
- Parameters:
- batch_size – int (default value of 100)
- records – List[
Record] - max_parallel_threads – int (default value of 6)
- Returns: None
property records
List of Record objects to be processed.
- Returns:
List[
Record]
fetch_release_states(parallelise=False)
Fetches the release states of the specified Record objects from the server, and populates their
relevant properties.
- Parameters:
parallelise – bool (splits operation into multiple threads if set to
True) - Returns: None
BulkRecordDeleterWithdrawer
class BulkRecordDeleterWithdrawer(session, records, batch_size=100, max_parallel_threads=6, withdrawal_notes=None)
Allows for bulk deletion or withdrawal or records from the server. Records are withdrawn from version-controlled tables, otherwise they are deleted.
The deletion/withdrawal is performed by a method on the class; as such, the list of
Record objects for deletion, batch size, and number of threads in parallel can be edited post-creation.
__init__(session, records, batch_size=100, max_parallel_threads=6, withdrawal_notes=None)
- Parameters:
- Returns: None
property records
List of records to be deleted or withdrawn.
- Returns:
List[
Record]
delete_or_withdraw(parallelise=False)
Performs the deletion (or withdrawal, if the records are in a version-controlled table).
- Parameters:
parallelise – bool (splits operation into multiple threads if
True) - Returns: None
DataRevisionHistoryFetcher
class DataRevisionHistoryFetcher(_mi, records, batch_size=100, max_parallel_threads=6)
Bulk exporter for data revision history.
Fetches the data revision history for all attributes of the provided records and populates the
Record.data_revision_history property.
See AttributeFetcher to export attribute data.
__init__(_mi, records, batch_size=100, max_parallel_threads=6)
- Parameters:
- Returns: None
fetch_data_revision_history(parallelise=False)
Fetches the data revision history for all attributes of the provided records and populates the
Record.data_revision_history property.
- Parameters: parallelise – bool
Database and Table level
Database
class Database(_gdl_obj, _mi, _service_providers)
Represents an MI database, and provides access to its tables, unit systems, and record link groups.
__init__(_gdl_obj, _mi, _service_providers)
- Parameters:
- _gdl_obj – Foundation API
GRANTA_MIScriptingToolkit.DatabaseDetailclass - _mi –
Sessionobject
- _gdl_obj – Foundation API
- Returns: None
property mi
MI Session that was used to create or access the Database object. Used for any Service Layer calls made by
the Database.
- Returns:
Sessionobject
property parameters
Parameters associated with the database, indexed by name.
- Returns:
Dict[str,
ParameterDefinition]
refetch_unit_systems()
Fetches the unit systems associated with the database. Makes a Service Layer call.
- Returns: None
dimensionally_equivalent_units(unit)
Returns all units which are dimensionally equivalent to the specified unit, with conversion factor and offset. Makes a single call to the Service Layer and caches the results.
- Example:
db.dimensionally_equivalent_units(unit='kg')might return{'g': {'factor': 1000.0, 'offset': 0.0}}. - Parameters: unit – str
- Returns: Dict[str, Dict[str, float]]
property unit_systems_available
Names of unit systems associated with the database.
- Returns: List[str]
set_unit_system(unit_system, absolute_temperatures=False)
Sets the unit system for the Database object. The default unit system is the same as for the database
itself.
- Parameters:
- unit_system – str
- absolute_temperatures – bool (Whether to use absolute temperature units or not)
- Returns: None
property absolute_temperatures
Whether the Database uses absolute temperature units (Kelvin/Rankine) or not (Celsius/Fahrenheit).
- Returns: bool
property unit_system
Currently selected unit system (default is DATABASE_UNIT_SYSTEM).
- Returns: str
get_all_link_details_where(name, table_name=None, to_table_name=None, to_db_key=None, rlg_types=None)
Returns all the named Foundation API GRANTA_MIScriptingToolkit.RecordLinkGroupDetail
objects that match the specified criteria.
- Parameters:
- name – str (Name of
GRANTA_MIScriptingToolkit.RecordLinkGroupDetailobject) - table_name – Optional[str]
- to_table_name – Optional[str]
- to_db_key – Optional[str]
- rlg_types – Optional[List[str]]
- name – str (Name of
- Returns:
list of Foundation API
GRANTA_MIScriptingToolkit.RecordLinkGroupDetailclass
get_link_detail(name, table_name=None, to_table_name=None, to_db_key=None, rlg_type=None)
Returns the named Foundation API GRANTA_MIScriptingToolkit.RecordLinkGroupDetail object.
Must resolve to exactly one record link group.
- Parameters:
- name – str (Name of
GRANTA_MIScriptingToolkit.RecordLinkGroupDetailobject) - table_name – str
- to_table_name – str
- to_db_key – str
- rlg_type – str
- name – str (Name of
- Returns:
Foundation API
GRANTA_MIScriptingToolkit.RecordLinkGroupDetailclass
property link_details
Foundation API GRANTA_MIScriptingToolkit.RecordLinkGroupDetail objects associated with the database.
- Returns:
List[
GRANTA_MIScriptingToolkit.RecordLinkGroupDetail]
property record_link_groups
All record link groups in the database.
- Returns:
List[
LinkGroupDetails]
property db_key
Database key.
- Returns: str
property name
Name of the database.
- Returns: str
property guid
GUID of the database.
- Returns: str
property version_guid
Version GUID of the database.
- Returns: str
refresh_tables()
Updates the list of tables associated with the database. Makes a Service Layer call.
- Returns: None
property tables
Tables associated with the database.
- Returns:
List[
Table]
property tables_by_name
Tables in the database, as dictionary keyed by name.
- Returns:
Dict[str,
Table]
property tables_by_guid
Tables in the database, as dictionary keyed by GUID.
- Returns:
Dict[str,
Table]
get_table(name, subsets=None, unit_system='Database', absolute_temperatures=False)
Returns the Table object with the specified name. Case-insensitive.
If the subsets argument is not provided, the default subset is applied to the returned table. Set
subsets to an empty set to disable subset filtering.
- Parameters:
- name – str
- subsets – Set[str] (default value of
None) - unit_system – str (default value of
DATABASE_UNIT_SYSTEM) - absolute_temperatures – bool (default value of
False)
- Returns:
Tableobject
get_table_by_guid(guid, subsets=None, unit_system='Database', absolute_temperatures=False)
Returns the Table object with the specified GUID. Case-insensitive.
If the subsets argument is not provided, the default subset is applied to the returned table. Set
subsets to an empty set to disable subset filtering.
- Parameters:
- guid – str
- subsets – Set[str] (default value of
None) - unit_system – str (default value of
DATABASE_UNIT_SYSTEM) - absolute_temperatures – bool (default value of
False)
- Returns:
Tableobject
search_for_records_by_name(name)
Performs a search on record name across the database. Returns only the Record objects whose
short or long names are an exact match for name. Case-insensitive. This method searches in the
currently active subsets for each table, and will raise an exception if a table has more than one
active subset.
Makes a separate Service Layer call for each table in the database.
Note: Use Table.search_for_records_by_name() to narrow your search to a single table.
- Parameters: name – str
- Returns:
List[
Record]
search_for_records_by_text(text)
Performs a simple text search across the database for the string provided. Returns a list of matching
Record objects. This method does not apply any subset filtering.
Makes a separate Service Layer call for each table in the database.
Note: Use Table.search_for_records_by_text() to narrow your search to a single table.
- Parameters: text – str
- Returns:
List[
Record]
search_for_records_where(list_of_criteria, silent=True)
Performs a search using criteria within tables across the database. Returns a list of matching Record
objects. If silent is True then errors caused by non-existent attributes will be ignored and no results
will be returned, otherwise the method will raise an exception.
Note: Use Table.search_for_records_where() to narrow your search to a single table.
- Parameters:
- list_of_criteria – List[
SearchCriterion] - silent – bool
- list_of_criteria – List[
- Returns:
List[
Record]
get_records_by_ids(record_identifiers)
Returns a Record object for each identifier provided. The returned list of records
will have the same number of elements as the provided list of identifiers. If no record corresponds
to that identifier then the corresponding item in the returned list will be None.
Each element in the record_identifiers parameter should be a dictionary with one or more of the
following (sets of) references in priority order:
vguid(Record GUID - uniquely identifies specific version of record)history_identity(Record history identity - uniquely identifies record only), and optionallyversion_number(Record version number)hguid(Record History GUID - uniquely identifies record only)
If vguid or version_number are not provided for version controlled records, this method will
return the latest available version of the record available to the user. The latest available version
is dependent on the user’s Granta MI permissions.
- Parameters: record_identifiers – Sequence[Dict[str, Union[str, int]]]
- Returns:
List[
Record]
get_record_by_id(hguid=None, vguid=None, history_identity=None, version_number=None)
Returns the Record object with the following (sets of) references in priority order:
vguid(Record GUID - uniquely identifies specific version of record)history_identity(Record history identity - uniquely identifies record only), and optionallyversion_number(Record version number)hguid(Record History GUID - uniquely identifies record only)
If vguid or version_number are not provided for version controlled records, this method will
return the latest available version of the record available to the user. The latest available version
is dependent on the user’s Granta MI permissions.
- Parameters:
- hguid – str (Record History GUID - uniquely identifies record)
- vguid – str (Record GUID - uniquely identifies record version)
- history_identity – int (Record history identity)
- version_number – int (Record version number)
- Returns:
Recordobject
Table
class Table(_gdl_obj, _mi, _service_providers, unit_system='Database', absolute_temperatures=False)
Represents an MI table, and provides access to records (particularly searching on record properties), exporters and attribute definitions.
NOTE
Do not create new instances of this class; it represents a pre-existing database structure.
__init__(_gdl_obj, _mi, _service_providers, unit_system='Database', absolute_temperatures=False)
- Parameters:
- _gdl_obj – Foundation API
GRANTA_MIScriptingToolkit.TableDetailclass - _mi –
Sessionobject - _service_providers –
BackendServiceCollectionobject - unit_system – str (Unit system to use in this table, e.g. ‘UK Imperial’. Default
value of
DATABASE_UNIT_SYSTEM.) - absolute_temperatures – bool (Whether to use absolute temperatures)
- _gdl_obj – Foundation API
- Returns: None
property unit_system
Unit system currently in use.
- Returns: str
set_display_unit(attribute, unit_symbol)
Sets the display unit for a POIN or RNGE attribute. This only affects display, not import or
FEA exporters.
- Parameters:
- attribute – Union[str, AttributeDefinitionPoint, AttributeDefinitionRange] (str must be the attribute name)
- unit_symbol – str
- Returns: None
reset_display_unit(attribute)
Resets the display unit for a POIN or RNGE attribute back to the unit system default.
- Parameters: attribute – Union[str, AttributeDefinitionPoint, AttributeDefinitionRange] (str must be the attribute name)
- Returns: None
property min_max_type
How table-wide minimum and maximum values of point (POIN), integer (INPT), range (RNGE) and
date-time (DTTM) attributes in the table are calculated:
None: Does not calculate values (can improve performance when loading tables)Approximate(default): Uses a fast, approximate algorithmExact: Takes account of current subset and permissions (can be slow on large tables)
Setting this property refreshes all attributes in the table, and makes a Service Layer call.
- Returns: str
refresh_subsets()
Fetches the list of subsets which can be applied to this table. Makes a Service Layer call.
- Returns: None
property subsets_available
Subsets which can be applied to this table.
- Returns: Set[str]
property default_subset
The default subset for this Table.
- Returns: str
property subsets
Subsets that are currently applied to the Table object. Used for record creation, searching,
and record fetching.
WARNING
If using any Table method which returns a list of records, such as a search method or
Table.all_records(), you must ensure that only one subset is currently applied to the
table. Otherwise a ValueError will be raised.
- Returns: Set[str]
add_subsets(values)
Adds single or multiple subsets to the list of subsets currently applied to the Table object.
- Parameters: values – Set[str], Tuple[str] or List[str]
- Returns: None
remove_subsets(values)
Removes single or multiple subsets from the list of subsets currently associated with the Table object.
- Parameters: values – Set[str], Tuple[str] or List[str]
- Returns: None
all_records(include_folders=False, include_generics=True, filter_by_subset=True, subset_name=None)
Returns a flattened list of all records in the table and populates the children property
of each Record object. If filter_by_subset is True then the operation will only
return records that are in the subset given in subset_name, if no value is provided then
the subset specified on the table will be used. If filter_by_subset is False then records
will be returned from all subsets. Makes a Service Layer call.
- Parameters:
- include_folders – bool
- include_generics – bool
- filter_by_subset – bool
- subset_name – str
- Returns:
List[
Record]
WARNING
If you set filter_by_subset to True, you must provide a subset_name or ensure that the table
has only one subset applied. If more than one subset is applied, this will raise a ValueError.
search_for_records_by_text(text, filter_by_subset=True, subset_name=None)
Performs a simple text search within the table for the specified string. Returns a list of matching
Record objects. If filter_by_subset is True then the search will only return records that
are in the subset given in subset_name, if no value is provided then the subset specified on the
table will be used. If filter_by_subset is False then records will be returned from all subsets.
Makes a Service Layer call.
WARNING
If you set filter_by_subset to True, you must provide a subset_name or ensure that the table being
searched has only one subset applied. If more than one subset is applied, this will raise a ValueError.
NOTE
Use Database.search_for_records_by_text() to search across the whole database.
- Parameters:
- text – str
- filter_by_subset – bool
- subset_name – str
- Returns:
List[
Record]
search_for_records_where(list_of_criteria, silent=False, filter_by_subset=True, subset_name=None)
Performs a search using criteria within the table. Returns a list of matching Record objects.
If silent is True then errors caused by non-existent attributes will be ignored and no results
will be returned, otherwise the method will raise an exception.
If filter_by_subset is True then the search will only return records that
are in the subset given in subset_name, if no value is provided then the subset specified on the
table will be used. If filter_by_subset is False then records will be returned from all subsets.
WARNING
If you set filter_by_subset to True, you must provide a subset_name or ensure that the table being
searched has only one subset applied. If more than one subset is applied, this will raise a ValueError.
NOTE
Use Database.search_for_records_where() to search across the whole database.
- Parameters:
- list_of_criteria – List[
SearchCriterion] - silent – bool
- filter_by_subset – bool
- subset_name – str
- list_of_criteria – List[
- Returns:
List[
Record]
property name
Name of the table.
- Returns: str
property guid
GUID of the table.
- Returns: str
property db_key
Parent database key.
- Returns: str
refresh_attributes()
Performs a Foundation API BrowseService.GetAttributeDetails() request and creates a new set
of attributes for the table from the results.
Makes a Service Layer call.
- Returns: None
property layouts
Fetch and view the layouts available in this table for Granta products.
- Returns:
Dict[str,
TableLayout]
property attributes
All attributes included in the table schema, indexed by name. Meta-attributes are accessible through the
meta_attributes property of their parent attribute.
- Returns:
Dict[str,
AttributeDefinition]
property mi
MI Session that was used to create or access the Table object. Used for any Service Layer calls made by
the Table.
- Returns:
Sessionobject
property database
Database in which the Table is defined.
- Returns:
Databaseobject
get_attribute_definition(name=None, identity=None)
Returns the AttributeDefinition object specified by name or the identifier identity.
Meta-attributes are also returned if the identifier is provided.
- Parameters:
- name – str (Name of the
AttributeDefinitionobject) - identity – int (Attribute identifier)
- name – str (Name of the
- Returns:
AttributeDefinitionobject or List[AttributeDefinition]
get_records_by_ids(record_identifiers)
Returns a Record object for each identifier provided. The returned list of records
will have the same number of elements as the provided list of identifiers. If no record corresponds
to that identifier in this table then the corresponding item in the returned list will be None.
Each element in the record_identifiers parameter should be a dictionary with one or more of the
following (sets of) references in priority order:
vguid(Record GUID - uniquely identifies specific version of record)history_identity(Record history identity - uniquely identifies record only), and optionallyversion_number(Record version number)hguid(Record History GUID - uniquely identifies record only)
If vguid or version_number are not provided for version controlled records, this method will
return the latest available version of the record available to the user. The latest available version
is dependent on the user’s Granta MI permissions.
This method can return records outside the currently selected subset.
- Parameters: record_identifiers – Sequence[Dict[str, Union[str, int]]]
- Returns:
List[
Record]
get_record_by_id(history_identity=None, hguid=None, vguid=None, version_number=None)
Returns the Record object with the following (sets of) references in priority order:
vguid(Record GUID - uniquely identifies specific version of record)history_identity(Record history identity - uniquely identifies record only), and optionallyversion_number(Record version number)hguid(Record History GUID - uniquely identifies record only)
If vguid or version_number are not provided for version controlled records, this method will
return the latest available version of the record available to the user. The latest available version
is dependent on the user’s Granta MI permissions.
This method can return records outside the currently selected subset.
- Parameters:
- history_identity – int (Record history identity)
- hguid – str (Record History GUID - uniquely identifies record)
- vguid – str (Record GUID - uniquely identifies record version)
- version_number – int (Record version number)
- Returns:
Recordobject or None
get_record_by_lookup_value(attribute_name, lookup_value)
Returns a Record object specified by attribute name and a exact match for a short text string
(lookup value), provided that:
-
The
lookup_valuematches exactly one record in the table. -
The record is in the default subset of the table.
-
Parameters:
- attribute_name – str
- lookup_value – str
-
Returns:
Recordobject or None
property children
Return the children of the Table node. Analogous to Record.children, this returns all the records one
level from the Table root.
Records returned by this property may have been cached from previous calls to Table.refetch_children() or
Table.all_records(), which apply subset filtering. If the Table subset configuration has
since been updated, refresh the list of children via one of the methods listed.
If there is no cached list of children, children are dynamically fetched on property access via
refetch_children(). The default subset filtering behavior is applied.
WARNING
You must ensure that the table has only one subset applied. If more than one subset is applied, this will raise a ValueError when dynamically retrieving children records.
- Returns:
List[
Record]
refetch_children(filter_by_subset=True, subset_name=None)
Refreshes the list of direct children belonging to the table. If filter_by_subset is True then the
operation will only return records that are in the subset given in subset_name, if no value is
provided then the subset specified on the table will be used. If filter_by_subset is False then
records will be returned from all subsets. Makes a Service Layer call.
- Parameters:
- filter_by_subset – bool
- subset_name – str
- Returns: None
WARNING
If you set filter_by_subset to True, you must provide a subset_name or ensure that the table
has only one subset applied. If more than one subset is applied, this will raise a ValueError.
search_for_records_by_name(name, filter_by_subset=True, subset_name=None)
Performs a search on record name within the table. Returns only the Record objects whose
short or long names are an exact match for name. If filter_by_subset is True then the search
will only return records that are in the subset given in subset_name, if no value is provided then
the subset specified on the table will be used. If filter_by_subset is False then records will be
returned from all subsets. Makes a Service Layer call. This method is Case-insensitive.
WARNING
If you set filter_by_subset to True, you must provide a subset_name or ensure that the table being
searched has only one subset applied. If more than one subset is applied, this will raise a ValueError.
NOTE
Use Database.search_for_records_by_name() to search across the whole database.
- Parameters:
- name – str
- filter_by_subset – bool
- subset_name – str
- Returns:
List[
Record]
create_empty_attribute_value(definition)
Create an empty AttributeValue instance for an attribute from its
AttributeDefinition.
This can subsequently be assigned to a record for import.
- Parameters:
definition –
AttributeDefinitionobject - Returns:
AttributeValueobject
create_record(name, parent=None, short_name=None, attributes=None, folder=False, subsets=None, release_record=False, color=RecordColor.InheritFromParent)
Creates a new Record object in the Table. The record will not exist
in MI, or be able to be assigned as a parent, until it is pushed to the server.
- Parameters:
- name – str (Long name)
- parent –
RecordorTableobject - short_name – str
- attributes – Dict[str,
AttributeValue] - folder – bool (Whether the record will be Folder type)
- release_record – bool (Whether the record will be released when it is next updated)
- subsets – Set[str] (List of subsets the record will belong to)
- color – Union[str, RecordColor] (Record color - Inherits from parent by default)
- Returns:
Recordobject
paths_from(paths)
Create multiple paths between specified start and end nodes in the table tree.
Paths are specified as a list of dictionaries with the following structure:
{'starting_node': Optional[Record],
'tree_path': ['list', 'of', 'folders'],
'end_node': '<end node string>',
'color': 'color for all new nodes to be assigned'}
See description of path_from() for further details.
- Parameters:
paths – List[Dict[str, Union[
Record, str, None, List[str]]]] - Returns:
List[Tuple[dict,
Record]]
path_from(starting_node, tree_path, end_node=None, color=RecordColor.InheritFromParent)
Ensures that all the folders in a specified path are available, and creates any that do not already exist.
- Parameters:
- starting_node – A
RecordorNone. Identifies the node under which the new path will start. Set toNoneto start the path at the root of the table. Set to an existing record/folder to create the path from the specified node. - tree_path – List[str] The names of the folders in the path, e.g.
['Polymers', 'Plastics', 'Thermoplastics', ...]. Folders in the path will be created if they don’t already exist. Existing records on the path will be converted to generic records. - end_node – str (Optional) The name of a new record that will be created below the last path node.
- color –
RecordColor(Optional) Sets the color of all folders and records in the path.
- starting_node – A
- Returns:
The
Recordobject at the end of the path: the created record ifend_nodehas been specified, otherwise the last folder in the path.
get_records_from_path(starting_node, tree_path, use_short_names=False)
Return all of the records that are found at the end of the path from a specified node.
- The starting node identifies the node immediately above the path. To start the path at the top of the tree,
set
starting_nodetoNone. To start the path under any other node in the tree, specify aRecordas thestarting_node. - Specify the path as a list of record names e.g.
['Polymers', 'Plastics', 'Thermoplastics', ...]. - You can include “wildcards” in the path by setting a node to ‘None’ e.g.
['Thermoplastics', 'None', 'Unfilled', ...]. - By default, the strings specified in the path list are assumed to be record full names; to specify the path
using record short names instead, set
use_short_namesto True.
Example 1:
recs = table.get_records_from_path(None, ['Record 1', None, 'Record 2'])
will return all records that are children of a record named Record 2, that also have Record 1 as a great-grandparent. The grandparent is set as a wildcard, and so any is allowed.
Example 2:
recs = table.get_records_from_path(None, ['Record 1', 'Record 3', None])
will return all records that are grandchildren of records named Record 3 that also have a great-grandparent called Record 1.
Both of these examples have assumed that Record 1 is a top-level record (and have a starting node as a table object to reflect this), but the method does not require this. The starting node can be any record object in the tree.
- Parameters:
- starting_node – any
Recordin the table tree. To start the path at the root node of the table tree, set toNone. - tree_path – a list of strings specifying the names of the records in the path. May include ‘None’ as a wildcard.
- use_short_names – a boolean that specifies whether the strings in the path are the record short names
- starting_node – any
- Returns: returns a list of records
- Return type:
List[
Record]
bulk_fetch(records, attributes=None, batch_size=100, parallelise=False, max_num_threads=6, include_binary_data=False)
Populates data values for all named AttributeDefinition and PseudoAttributeDefinition objects in
the specified Record objects. Set attributes to None to export all record data.
Attribute values for requested attributes are added to Record.attributes dictionary whether the
attribute is populated or not.
Meta-attributes can be included in a bulk operation by providing the meta-attribute AttributeDefinition
in attributes. AttributeDefinition of meta-attributes can be obtained from the parent attribute
AttributeDefinition.meta_attributes.
Attribute values will not be created for attributes not included in the export via the attributes argument and
trying to access them might raise a KeyError.
If include_binary_data is set to False (default), the export will not fetch the binary data
representing the request File and Picture attributes and will instead export URLs (see the
BinaryType.url documentation for more information on how to use the URL to access the data). This
setting is recommended for large files and pictures, or if the binary data itself is not required.
To summarize how the file and picture data can be accessed:
include_binary_data = False(default): TheBinaryType.urlproperty is populated.include_binary_data = True: TheBinaryType.binary_dataproperty, andAttributeFile.save()andAttributePicture.save()methods are both available to access and save the binary data. TheBinaryType.urlproperty is empty and returnsNone.
This operation performs no subset filtering, so all tabular rows will be included in the response regardless of the subset membership of the linked records.
WARNING
If include_binary_data is set to False, the binary_data property and save() method are
both still available for backwards compatibility. However, they will download the data from Granta MI on
demand for each attribute value. A warning will be generated each time this occurs, although the default
warning configuration in Python is to only display each warning once.
This behavior is likely to have a significant performance impact, and so it is recommended that if access to
the binary data is required without the HTTP GET request, you should specify include_binary_data = True.
This performance impact will also be evident during the re-import of File or Picture attributes, or
tabular attributes that contain File or Picture columns. It is strongly recommended to set
include_binary_data = True if any File or Picture data will be re-imported into Granta MI.
On-demand access to attribute values without using Table.bulk_fetch() is unaffected.
NOTE
Providing a list of attributes by name or by AttributeDefinition will not fetch any meta-attributes
associated with those attributes. If the meta-attributes are not explicitly requested, then the resulting
AttributeValue.meta_attributes dictionary will contain empty meta-attribute values.
The following code snippet shows how to include meta-attributes and pseudo-attributes in a bulk_fetch
request:
table = db.get_table("MaterialUniverse")
attribute_names = ["Density", "Price", "Young's modulus"]
print("Fetch three attributes by name")
table.bulk_fetch(records, attributes=attribute_names)
attribute_definitions = [table.attributes[name] for name in attribute_names]
print("Fetch three attributes by AttributeDefinition")
table.bulk_fetch(records, attributes=attribute_definitions)
attr_and_meta_definitions = attribute_definitions + [meta_attr
for attr in attribute_definitions
for meta_attr in attr.meta_attributes.values()]
print("Fetch three attributes and their meta-attributes")
table.bulk_fetch(records, attributes=attr_and_meta_definitions)
attr_meta_and_pseudo_definitions = attr_and_meta_definitions + mpy.RecordProperties.all()
print("Fetch three attributes, their meta-attributes, and all pseudo-attributes")
table.bulk_fetch(records, attributes=attr_meta_and_pseudo_definitions)
- Parameters:
- attributes – List[Union[
AttributeDefinition,PseudoAttributeDefinition, str]] - records – List[
Record] - batch_size – int (default value of 100)
- parallelise – bool
- max_num_threads – int (default value of 6)
- include_binary_data – bool (default value of False)
- attributes – List[Union[
- Returns: None
bulk_link_fetch(records, link_groups=None, batch_size=100, parallelise=False, max_num_threads=6, filter_subsets=True)
Fetches and populates record link groups for the specified Record
objects. Set link_groups to None to fetch all record link groups.
Set filter_subsets to True to return records that are in the
default subsets of the target table. Set it to False to search without
filtering by subset.
- Parameters:
- records – List[
Record] - link_groups – List[str]
- batch_size – int (default value of 100)
- parallelise – bool
- max_num_threads – int (default value of 6)
- filter_subsets – bool (default value of
True)
- records – List[
- Returns: None
bulk_fetch_associated_records(records, target_table, link_direction='Both', attribute_path=None, batch_size=100, parallelise=False, max_num_threads=6)
Fetches records associated with the specified Record objects from a target Table. Returns a list
of dictionaries containing the source record and associated records for each Record provided.
You may specify link_direction to only follow tabular links in the specified direction, or provide a list of
AttributeDefinitionTabular objects in attribute_path to follow only those tabular links.
- Parameters:
- records – List[
Record] - target_table –
Table - link_direction – str (
Both(default),Forward,Reverse) - attribute_path – List[
AttributeDefinitionTabular] - batch_size – int (default value of 100)
- parallelise – bool
- max_num_threads – int (default value of 6)
- records – List[
- Returns:
List[Dict[str, Union[
Record, List[Record]]]]
bulk_fetch_data_revision_history(records, batch_size=100, parallelise=False, max_num_threads=6)
Fetches the data revision history for all attributes of the provided records and populates the
Record.data_revision_history property.
- Parameters:
- records – List[
Record] - batch_size – int (default value of 100)
- parallelise – bool
- max_num_threads – int (default value of 6)
- records – List[
- Returns: None
get_available_exporters(package=None, model=None, applicability_tag=None)
Returns exporters available on the table filtered by package, model, and applicability tag value.
- Parameters:
- package –
strThe target FEA analysis package. For example: ‘NX 10.0’, ‘CATIA V5’. - model –
strThe material model type. For example, ‘Isotropic’, ‘Linear, temperature-independent, isotropic, thermal, plastic’. - applicability_tag –
strA tag that identifies the applications for which an exporter is intended to be used. For example, ‘MIMaterialsGateway’, ‘MIViewer’.
- package –
- Returns:
List[
Exporter]
LinkGroupDetails
class LinkGroupDetails(link_detail)
Provides access to the properties of a record link group.
__init__(link_detail)
- Parameters:
link_detail – Foundation API
GRANTA_MIScriptingToolkit.RecordLinkGroupDetailclass - Returns: None
property name
Name of the record link group.
- Returns: str
property table_to
Name of the table from which the link group originates.
- Returns: str
property table_from
Name of the table the link group comes from.
- Returns: str
property type
Whether the record link group is ‘static’, ‘cross-database’ or ‘dynamic’.
- Returns: str
property reverse_name
Name of the record link group in the return direction.
- Returns: str
TableLayout
class TableLayout(name, table)
Provides a JSON-format display of a Granta layout. You can access this through the layout property.
NOTE
Do not create new instances of this class manually.
__init__(name, table)
- Parameters:
- name – str
- table –
Tableobject
- Returns: None
property name
Layout name.
- Returns: str
property layout
JSON-formatted version of the layout.
- Returns: List[Dict[str, Union[str, List[str], Dict[str, Union[str, List[str]]]]]]
property categories
List of all the categories (headings) in the layout.
- Returns: List[str]
property attributes_by_category
Dictionary of attribute lists, indexed by the layout category they are in.
- Returns: Dict[str, List[str]]
property link_groups_by_category
Dictionary of link group lists, indexed by the layout category they are in.
- Returns: Dict[str, List[str]]
property meta_attributes_by_attribute
Dictionary of meta-attribute lists, indexed by parent attributes.
- Returns: Dict[str, List[str]]
meta_attributes_on(attribute_name)
Returns the list of meta-attributes corresponding to a given attribute in this layout.
- Parameters: attribute_name – str
- Returns: List[str]
Exporter
class Exporter(mi, exporter_key)
__init__(mi, exporter_key)
Represents a Granta MI FEA exporter. FEA exporters are used to export record data from Granta MI into formats supported by CAD and CAE packages.
This operation performs no subset filtering, so all tabular rows will be included in the Initial XML regardless of the subset membership of the linked records.
- Parameters:
- mi – Current
Sessionobject - exporter_key – str (Unique identifier for this exporter)
- mi – Current
- Returns: None
property default_file_extension
Returns the default file extension as defined by the exporter configuration file.
- Returns: str
save(file_path, file_name=None, file_extension=None)
Saves the output of the last FEA export to the path provided using the default naming convention and file extension for the exporter; specify a file_name or file_extension to override the defaults.
- Parameters:
- file_path – str (File path of the form C:\Users\Username\)
- file_name – str (Optional - Output file name. Does not require a file extension.)
- file_extension – str (Optional - Output file extension.)
- Returns: None
property default_file_name
Returns the default file name for the last performed export, as defined by the exporter configuration file.
- Returns: str
property default_encoding
Returns the default file encoding scheme as defined by the exporter configuration file.
NOTE
This is returned as a Python-compatible string (e.g. “cp1252”) rather than the .NET codepage “1252”.
- Returns: str
property default_bom
Returns the default byte-order mark as defined by the exporter configuration file. If no BOM is required by
default, this property is None.
- Returns: Union[str, None]
get_parameters_required_for_export(records)
Returns a dictionary of all the parameter definitions the Exporter requires to export the data from the specified list of records, indexed by parameter name.
- Parameters:
records – List[
Record] - Returns:
Dict[str,
ParameterDefinition]
run_exporter(records, stop_before=None, parameter_defs=None, sig_figs=None)
Performs an FEA export on the specified list of records, returning the data representing the records as a string.
- Parameters:
- records – List[
Record] - stop_before – Union[int, str] (Either refers to the index of the transform step (int) or its name (str))
- parameter_defs – Dict[str,
ParameterDefinition] - sig_figs – int
- records – List[
- Returns: str (Contains data output by the exporter)
export_list_is_valid(records)
Verifies that a list of records is valid for export.
If the exporter was created from a table search, then this method verifies that all records come from this table. Otherwise, the first record is used to determine which table the exporter belongs to.
- Parameters:
records – List[
Record] - Returns: bool (Whether the specified list of records can be exported with this exporter)
Record level
Record
class Record(name, table, parent=None, short_name=None, attributes=None, subsets=None, folder=None, record_color=None, release_record=True)
Stores and provides access to record attributes, pseudo-attributes, links and children. Provides methods for adding, editing and deleting records, and importing/exporting record data.
New Record objects may be created to represent records that do not currently exist in the database:
- A name and parent table must be specified.
namewill become the record’s long name. The record short name (or tree name) can be set via the argumentshort_name, or via theRecord.short_nameproperty following object creation. If a record is pushed to MI without a specifying short name, the short name will default to the record name. - Records created this way will not exist in the host database until the changes have been
pushed to MI (see
Session.update()).
NOTE
Do not create new instances of Record objects for records which are already in the database.
Existing records will have Foundation API classes associated with them, from which the Streamlined API will
automatically generate and return Record objects as required.
__init__(name, table, parent=None, short_name=None, attributes=None, subsets=None, folder=None, record_color=None, release_record=True)
- Parameters:
- name –
str(Long name for new records) - table –
Tableobject - parent –
RecordorTableobject - short_name –
str(Short (tree) name for new records) - attributes – Dict[
str,AttributeValue] - subsets – Set[
str] (Subsets the record belongs to) - folder –
bool(Whether the record is ‘Folder’ type) - record_color –
RecordColor(Color of the record) - release_record –
bool(Release state of the record;Trueto release next version)
- name –
- Returns: None
property name
Long name of record.
If the Record object represents an existing record:
- The property will initially return the exported name of the record. It will be fetched if it has not already been exported.
- If the property is modified, the
Recordname will be set to the specified value. - If the property is set to
None, theRecordname will be reset to the exported value.
If the Record object represents a new record:
- The property will initially return the value specified in the
Recordconstructor. - If the property is modified, the
Recordname will be set to the specified value. - If the property is set to
None, theRecordname will be set toNone.
NOTE
If a Record is imported with name set to None, a ValueError will be
raised.
- Return type: str
property mi
MI Session that was used to create or access the record.
Used for any Service Layer calls made by the Record object.
- Returns:
Sessionobject
property table
Parent Table the record belongs to.
- Returns:
Tableobject
property table_name
Name of parent table.
- Returns: str
property db_key
Database key for the database the record belongs to.
- Returns: str
property subsets
Subsets that the record belongs to.
- Returns: Set[str]
property flag_for_release
Whether the record will be made available to users when it is next updated.
True(default): If changes were made to theRecord, a new version will be created, otherwise the unreleased version of the record will be released when the server is updated.False: If changes were made to theRecord, a new, unreleased version will be created when the server is updated.
NOTE
If you do not have the correct permissions to change release states, setting this property will not have the documented effect. Please see the Service Layer documentation for more details.
- Returns: bool or None
property color
Color of the record when displayed in MI Viewer and other Granta MI applications.
If the Record object represents an existing record:
- The
colorproperty will initially return the exported color of the record. It will be fetched if it has not already been exported. - If
coloris modified, theRecordcolor will be set to the specified value. - If
coloris set toNone, theRecordcolor will be reset to the exported value.
If the Record object represents a new record:
- The
colorproperty will initially return the value specified in theRecordconstructor. If not set, it will default to the value InheritFromParent. - If
coloris modified, theRecordcolor will be set to the specified value. - If
coloris set toNone, theRecordcolor will be set to the value InheritFromParent.
NOTE
If a Record is imported with color set to None, the record will
inherit the color of the parent record.
- Returns:
RecordColor
property short_name
Short (tree) name of the record.
If the Record object represents an existing record:
- The
short_nameproperty will initially return the exported short name of the record. It will be fetched if it has not already been exported. - If
short_nameis modified, theRecordshort name will be set to the specified value. - If
short_nameis set toNone, theRecordshort name will be reset to the exported value.
If the Record object represents a new record:
- The
short_nameproperty will initially return the value specified in theRecordconstructor. - If
short_nameis modified, theRecordshort name will be set to the specified value. - If
short_nameis set toNone, theRecordshort name will be set toNone.
NOTE
If a Record is imported with short_name set to None, the short name
will default to the record name.
- Returns: str, optional
property parent
Parent record or table of this record.
find_parent()
Finds and sets the parent record or table.
If a Record has been created from a Foundation API GRANTA_MIScriptingToolkit.RecordReference
object (for example, an existing database record), its parent may not be defined. This function gets the
Foundation API GRANTA_MIScriptingToolkit.TreeRecord object (if it does not already exist) and uses
it to create and/or set a parent Record object. If the record is at the highest level, the parent is
set as the host Table object instead.
Since the parent record is in all subsets that this record is in, this operation performs no subset filtering.
- Returns: None
property history_guid
Record History GUID, if it exists. Records can be uniquely identified by their Record History GUID, which will return the latest version the user has access to.
- Returns: str or None
property record_guid
Record GUID, if it exists. Each version of a record can be uniquely identified by its Record GUID.
- Returns: str or None
property history_identity
Record history identity, if it exists.
- Returns: int or None
set_attributes(attributes)
Flags attributes to update on the server when Session.update()
is next called. If set_attributes() is not called on modified attributes, changes
to those attributes will not be transferred to MI.
- Parameters: attributes – Union[Iterable[AttributeValue]]
- Returns: None
clear_attributes(attributes)
Flags attributes to have their data value on the server deleted when Session.update()
is next called. Does not delete the local value of flagged attributes, only the data on MI. Supersedes
previous set_attributes() calls.
- Parameters: attributes – Union[Iterable[AttributeValue]]
- Returns: None
property viewer_url
The MI Viewer URL for the record.
- Returns: str
property path
Browse tree path for the record as a list of folder short names.
- Returns: List[str]
property pseudo_attributes
Pseudo-attributes associated with the record, indexed by name.
NOTE
Supported names are:
recordTyperecordHistoryIdentityrecordColorrecordVersionNumbertableNamewritableparentShortNameparentNameparentRecordHistoryIdentityshortNamemodifiedDatecreatedDatereleasedDatelastModifiercreatorsubsetsname
WARNING
This property is deprecated. Pseudo-attribute values are available as properties:
Record.typeRecord.history_identityRecord.colorRecord.version_numberRecord.table_nameRecord.is_writableRecord.parent_record_short_nameRecord.parent_record_nameRecord.parent_record_history_identityRecord.short_nameRecord.last_modified_onRecord.created_onRecord.released_onRecord.last_modified_byRecord.created_byRecord.subsetsRecord.name
- Returns:
Dict[str,
PseudoAttributeValue]
refresh_path()
Re-calculates the record path within the current table.
Since all ancestor records are in all subsets that this record is in, this operation performs no subset filtering.
Makes a Service Layer call.
- Returns: None
property exists_on_server
Whether the record exists on the server (True) or has been created in memory (False).
- Returns: bool
refresh_properties()
Refreshes the Foundation API GRANTA_MIScriptingToolkit.TreeRecord object associated with the
Record, if it has one.
Makes a Service Layer call.
- Returns: None
refetch_children(filter_by_subset=True, subset_name=None)
Refreshes the list of children belonging to the record. If filter_by_subset is True then the
operation will only return records that are in the subset given in subset_name, if no value is
provided then the subset specified on the table will be used. If filter_by_subset is False
then records will be returned from all subsets. Makes a Service Layer call.
- Parameters:
- filter_by_subset – bool
- subset_name – str
- Returns: None
WARNING
If you set filter_by_subset to True, you must provide a subset_name or ensure that the table
has only one subset applied. If more than one subset is applied, this will raise a ValueError.
refresh_attributes()
Checks whether the record’s attributes have changed on the server, and updates the Record object if
required. Can also be used to populate attributes. Makes a Service Layer call.
Always includes binary data in the response. Use the bulk_fetch() method if URL
data representation is required.
- Returns: None
refetch_pseudos()
Fetches pseudo-attribute data for this record, and updates subsets for the record if not set. Makes a Service Layer call.
- Returns: None
property attributes
Attributes associated with the record, indexed by attribute name.
- Returns:
Dict[str,
AttributeValue]
get_attributes(names=None, types=None, include_attributes=True, include_metas=False, include_pseudos=False, empty=None)
Retrieve a list of attributes from the record.attributes dictionary. You can narrow the results by
specifying the attribute names or data types, or the required attribute categories (attribute,
meta-attribute, or pseudo-attribute).
If the record.attributes dictionary is empty when get_attributes is called, it will be
populated before retrieving any attributes.
This operation performs no subset filtering, so all tabular rows will be included in the response regardless of the subset membership of the linked records.
- Example:
r.get_attributes(names=['Density', 'Stress-Strain'], types=['POIN', 'FUNC'], include_metas=True)will return all point or functional series attributes or meta-attributes named Density or Stress-Strain from the record. - Parameters:
- names – List[str]
- types – List[str] (Attribute data types; allowed values are: DISC, DTTM, FILE, FUNC, HLNK, INPT, LOGI, LTXT, PICT, POIN, RNGE, STXT, TABL)
- include_attributes – bool (whether to retrieve attributes that are not meta-attributes or
pseudo-attributes;
Trueby default) - include_metas – bool (whether to retrieve meta-attributes;
Falseby default) - include_pseudos – bool (whether to retrieve pseudo-attributes;
Falseby default) - empty – bool (whether to check if the returned attributes are populated)
- Returns:
List[Union[
PseudoAttributeValue,AttributeValue]]
property type
Record type.
On record creation via the MI Scripting Toolkit, the record type can only be set to RecordType.Folder or
RecordType.Record. The type of an existing record cannot be set via this property.
Adding children to a record, or populating attributes on a folder both result in the type updating to
RecordType.Generic during the update.
- Return type: RecordType
all_children(include_folders=False, include_generics=True, filter_by_subset=True, subset_name=None)
Returns a flattened list of all descendants of a record and populates the children property of
each Record object traversed in the process.
WARNING
This method is deprecated. Use get_descendants().
get_descendants(include_folders=False, include_generics=True, filter_by_subset=True, subset_name=None)
Returns a flattened list of all descendants of a record and populates the children property of
each Record object traversed in the process.
If filter_by_subset is True then the operation will only return records that are in the subset given in
subset_name, if no value is provided then the subset specified on the table will be used.
If filter_by_subset is False then records will be returned from all subsets. Makes a Service Layer call.
- Parameters:
- include_folders – bool
- include_generics – bool
- filter_by_subset – bool
- subset_name – str
- Returns:
List[
Record]
WARNING
If you set filter_by_subset to True, you must provide a subset_name or ensure that the table
has only one subset applied. If more than one subset is applied, this will raise a ValueError.
property children
Records that are direct children of the current record.
Records returned by this property may have been cached from previous calls to
Record.get_descendants() (previously Record.all_children()), Record.refetch_children() or
Table.all_records(), which all apply subset filtering. If the Table subset configuration has
since been updated, refresh the list of children via one of the methods listed.
If there is no cached list of children, children are dynamically fetched on property access via
refetch_children(). The default subset filtering behavior is applied.
- Returns:
List[
Record]
WARNING
You must ensure that the table has only one subset applied. If more than one subset is applied, this will raise a ValueError when dynamically retrieving children records.
property links
Link groups for this Record object, and the records they link to. Smart links may be viewed but not
edited through the links property.
This operation performs no subset filtering.
- Returns:
Dict[str, Set[
Record]]
get_associated_records(target_table, link_direction='Both', attribute_path=None)
Gets all records in a target table that are linked to the current Record object via tabular data
association chains. This can be filtered by link direction and to a specific path.
If attribute_path is provided, then only records from that exact path will be returned. Note that the
specified tabular attributes will be the ‘source’ of the tabular link, and there may be tables in the chain
with no attributes.
This operation performs no subset filtering.
- Parameters:
- target_table –
Tableobject - link_direction – str (Which direction to follow links in:
Both(default),Forward,Reverse) - attribute_path – List[
AttributeDefinition] (Path of tabular attributes to follow - ifNone, all paths are followed)
- target_table –
- Returns:
List[
Record]
set_links(link_name, records)
Adds the specified records to the named record link group and flags those links for update. Links that are not set through this method will not be updated on the server.
- Parameters:
- link_name – str
- records – Iterable[
Record]
- Returns: None
decache_attributes()
Removes all attributes from the Record, replacing the attributes property with an empty
dictionary.
- Returns: None
decache_links()
Removes all links from the Record, setting the links property to None.
- Returns: None
property is_folder
Whether the record is a RecordType.Folder type.
- Returns: bool
property release_state
Release state of the record. Allowed values are ‘Released’, ‘Superseded’, ‘Withdrawn’, ‘Unreleased’, ‘Unversioned’ or ‘Unknown’.
- Returns: str
property record_history
Details about the record history. Includes user, datetime, and notes associated with events of the record’s life cycle.
- Returns:
RecordVersionHistory
refetch_record_release_state()
Fetches the record’s release state from the server. Makes a Service Layer call.
- Returns: None
property all_versions
Returns all versions or the record as dictionary of Record objects indexed by version number, and the
letter ‘v’, e.g. ‘v1’ or ‘v2’. In a version controlled table this can be many, and in a non-version-controlled
table there will only ever be one, with the key ‘v0’.
- Returns:
Dict[str,
Record]
refetch_record_versions()
Refetches version information and all visible versions of the record for this user. Makes a Service Layer call.
- Return None:
delete_or_withdraw_record_on_server(withdrawal_notes=None)
Deletes the record from the server, or withdraws it from a version-controlled table. Makes a Service Layer call.
- Parameters: withdrawal_notes – Optional[str], withdrawal revision notes.
- Returns: None
get_available_exporters(package=None, model=None, applicability_tag=None)
Returns exporters available for this record filtered by package, model, and applicability tag value.
- Parameters:
- package – str (Name of target FEA analysis package, for example ‘NX 10.0’ or ‘CATIA V5’)
- model – str (Material model type, for example ‘Isotropic’ or ‘Linear, temperature-independent, isotropic, thermal, plastic’)
- applicability_tag – str (Tag that identifies the MI applications an exporter is intended to be used with, for example, ‘MIMaterialsGateway’ or ‘MIViewer’)
- Returns:
List[
Exporter]
property data_revision_history
Data revision history for all attributes, indexed by attribute name.
- Returns:
Dict[str,
DataRevisionHistory]
move_to(new_parent)
Moves the record and all its descendants to a new parent.
The provided new parent must be a Record of type RecordType.Folder or
RecordType.Generic, or a Table to move the record at the root of the table.
Some cached properties are cleared after the record has been moved, as they would be out-of-date:
Record.pseudo_attributesand pseudo-attribute propertiesRecord.pathRecord.parent
They will be dynamically retrieved from the server on property access, or can be manually refreshed via the following methods:
Record.children is not cleared, because children are moved with the parent. Their internal state might
be outdated, and if necessary can be updated via the methods listed above.
children properties of the source and target parent are not cleared or updated. This is by design, to
prevent unnecessary updates in scripts performing a large number of record move operations.
To update the list of children of a table (after moving a child record from it or to it), use the method
Table.refetch_children().
To update the list of children of a record (after moving a child record from it or to it), use the method
Record.refetch_children().
property version_number
Record version number. This is set to None if the record is in a non version-controlled table.
Read-only property. This is only available for records that exist on the server.
This property is populated from a pseudo-attribute value and can be refreshed via refetch_pseudos().
- Return type: int | None
property is_writable
Whether the current user has write permissions on the record.
Read-only property. This is only available for records that exist on the server.
This property is populated from a pseudo-attribute value and can be refreshed via refetch_pseudos().
- Return type: bool
property parent_record_short_name
Short name of the parent record.
If the record is at the root of the table, returns the name of the table.
Read-only property. This is only available for records that exist on the server.
This property is populated from a pseudo-attribute value and can be refreshed via refetch_pseudos().
- Return type: str
property parent_record_name
Name of the parent record.
If the record is at the root of the table, returns the name of the table.
Read-only property. This is only available for records that exist on the server.
This property is populated from a pseudo-attribute value and can be refreshed via refetch_pseudos().
- Return type: str
property parent_record_history_identity
History identity of the parent record.
If the record is at the root of the table, returns the history identity of the table root node.
Read-only property. This is only available for records that exist on the server.
This property is populated from a pseudo-attribute value and can be refreshed via refetch_pseudos().
- Return type: int
property last_modified_on
Datetime of the last modification.
Read-only property. This is only available for records that exist on the server.
This property is populated from a pseudo-attribute value and can be refreshed via refetch_pseudos().
- Return type: datetime.datetime
property last_modified_by
User who last modified the record.
Read-only property. This is only available for records that exist on the server.
This property is populated from a pseudo-attribute value and can be refreshed via refetch_pseudos().
- Return type: str
property created_on
Datetime of the record creation.
Read-only property. This is only available for records that exist on the server.
This property is populated from a pseudo-attribute value and can be refreshed via refetch_pseudos().
- Return type: datetime.datetime
property created_by
User who created the record.
Read-only property. This is only available for records that exist on the server.
This property is populated from a pseudo-attribute value and can be refreshed via refetch_pseudos().
- Return type: str
property released_on
Datetime of the record release.
Read-only property. This is only available for records that exist on the server.
This property is populated from a pseudo-attribute value and can be refreshed via refetch_pseudos().
- Return type: datetime.datetime
Attribute level
There are two types of attribute object at the attribute level: Attribute Definitions and Attribute Values.
Attribute Definitions
These classes describe how an attribute appears in the schema of a given table. There are ten types.
- AttributeDefinition - Base class, and parent of all AttributeDefinition classes; covers all attributes not covered by those below
- AttributeDefinitionDiscrete - Child class covering discrete attributes
- AttributeDefinitionMultiValue - Child class covering multi-valued attributes such as functional, or point
- AttributeDefinitionPoint - Child class covering point attributes
- AttributeDefinitionRange - Child class covering range attributes
- AttributeDefinitionInteger - Child class covering integer attributes
- AttributeDefinitionDatetime - Child class covering datetime attributes
- AttributeDefinitionTabular - Child class covering tabular attributes
- AttributeDefinitionUnsupported - Child class covering unsupported attribute types (maths functional and discrete functional)
- PseudoAttributeDefinition - Class for pseudo-attributes. Operates like AttributeDefinition but is not a child of it.
AttributeDefinition
class AttributeDefinition(table)
__init__(table)
Base attribute definition class.
NOTE
Do not create new instances of this class; it represents a pre-existing database structure.
Stores basic information about an attribute, such as data type or possible values. Contains information about
the attribute itself, and cannot be used to set attribute values. AttributeDefinition wraps all
properties of the Foundation API GRANTA_MIScriptingToolkit.AttributeDetail object, including
properties that may not be populated for a given attribute. For example, axis_name will not always be
populated, but it will always be included because it is a property of
GRANTA_MIScriptingToolkit.AttributeDetail.
- Parameters:
table –
Tableobject - Returns: None
property table
Parent Table the attribute belongs to.
- Returns:
Tableobject
property id
Attribute identifier.
- Returns: int
property axis_name
Y-axis name (for functional data attributes only).
- Returns: str
property name
Attribute name.
- Returns: str
property order
Display order in MI Viewer.
- Returns: int
property is_meta
Whether the attribute is a meta-attribute or not.
- Returns: bool
property is_meta_for
Name of the parent attribute, if the attribute is a meta-attribute. Returns None if not a meta-attribute.
- Returns: str or None
property type
Attribute data type, as a four-character string. Possible attribute types are:
POIN = point,
RNGE = range,
FUNC = float functional,
INPT = integer,
LOGI = logical,
DISC = discrete,
STXT = short text,
LTXT = long text,
DTTM = date time,
HLNK = hyperlink,
PICT = picture,
FILE = file,
DSFN = discrete functional,
MAFN = maths functional (equations and logic),
TABL = tabular.
DSFN and MAFN are not supported by the MI Scripting Toolkit, and appear as UNSUPPORTED DATA TYPE.
- Returns: str
property unit
Unit symbol.
- Returns: str
property meta_attributes
Meta-attributes associated with this attribute, indexed by name.
- Returns:
Dict[str,
AttributeDefinition]
search_criterion(less_than=None, greater_than=None, contains=None, contains_any=None, contains_all=None, does_not_contain=None, exists=None, equal_to=None, between_dates=None, in_column=None)
Creates a search criterion for use with Table.search_for_records_where() or
Database.search_for_records_where().
Operator priority is the same as the order of the arguments.
- Parameters:
- less_than – float
- greater_than – float
- contains – Union[str, bool]
- contains_any – List[str]
- contains_all – List[str]
- does_not_contain – str
- exists – bool
- equal_to – Union[int, str]
- between_dates – Union[str, datetime.datetime] (Two dates in chronological order, str must be in YYYY-MM-DD format)
- in_column – str (Name of tabular column to search)
- Returns:
SearchCriterionobject
NOTE
To perform an exact search on a discrete attribute, use either the contains_any or
contains_all parameters. In the case of searching for a single discrete value, the argument
should be a list containing the search term.
property history
Revision history of the attribute, as an ObjectHistory object.
- Returns:
ObjectHistoryobject
AttributeDefinitionDiscrete
class AttributeDefinitionDiscrete(table)
__init__(table)
Extended AttributeDefinition class for discrete attributes.
Provides a method to view the possible discrete values of an attribute.
- Parameters:
table –
Tableobject - Returns: None
property discrete_values
All possible discrete values of the attribute.
- Returns: List[str]
property is_multivalued
Whether this attribute allows multiple values to be set.
- Returns: bool
AttributeDefinitionMultiValue
class AttributeDefinitionMultiValue(table)
__init__(table)
Extended AttributeDefinition class for functional and point data attributes.
Provides access to functional data parameters.
- Parameters:
table –
Tableobject - Returns: None
property parameters
Parameters associated with the attribute, indexed by name.
- Returns:
Dict[str,
ParameterDefinition]
AttributeDefinitionPoint
class AttributeDefinitionPoint(table)
__init__(table)
Extended AttributeDefinitionMultiValue class for point attributes.
Provides access to point-specific information and methods.
- Parameters:
table –
Tableobject - Returns: None
property is_multivalued
Whether this attribute allows multiple values to be set.
- Returns: bool
property max
Maximum value of the data attribute. Affected by user read permissions.
- Returns: Union[float, int, datetime.datetime]
property min
Minimum value of the data attribute. Affected by user read permissions.
- Returns: Union[float, int, datetime.datetime]
property unit
Unit symbol.
- Returns: str
AttributeDefinitionRange
class AttributeDefinitionRange(table)
__init__(table)
Extended AttributeDefinition class for range attributes.
Provides access to range-specific information and methods.
- Parameters:
table –
Tableobject - Returns: None
property max
Maximum value of the data attribute. Affected by user read permissions.
- Returns: Union[float, int, datetime.datetime]
property min
Minimum value of the data attribute. Affected by user read permissions.
- Returns: Union[float, int, datetime.datetime]
property unit
Unit symbol.
- Returns: str
AttributeDefinitionInteger
class AttributeDefinitionInteger(table)
__init__(table)
Extended AttributeDefinition class for integer attributes.
Provides access to integer-specific information, such as minmax.
- Parameters:
table –
Tableobject - Returns: None
property max
Maximum value of the data attribute. Affected by user read permissions.
- Returns: Union[float, int, datetime.datetime]
property min
Minimum value of the data attribute. Affected by user read permissions.
- Returns: Union[float, int, datetime.datetime]
AttributeDefinitionDatetime
class AttributeDefinitionDatetime(table)
__init__(table)
Extended AttributeDefinition class for date-time attributes.
Provides access to type-specific information, such as minmax.
- Parameters:
table –
Tableobject - Returns: None
property max
Maximum value of the data attribute. Affected by user read permissions.
- Returns: Union[float, int, datetime.datetime]
property min
Minimum value of the data attribute. Affected by user read permissions.
- Returns: Union[float, int, datetime.datetime]
AttributeDefinitionTabular
class AttributeDefinitionTabular(table)
__init__(table)
Extended AttributeDefinition class for tabular data attributes.
Provides access to tabular-specific information and methods, such as columns, linking attribute and cross-table links.
- Parameters:
table –
Tableobject - Returns: None
property linking_attribute
Linking attribute, a short text-type attribute used to link rows in the tabular data attribute to records.
Returns None for purely local tabular data or if the user cannot access the table in Granta MI.
- Returns:
AttributeDefinitionobject or None
property linking_table
Table object which the linking attribute belongs to. Returns None for purely local tabular data
or if the user cannot access the table in Granta MI.
- Returns:
Tableobject or None
property column_types
Data type in each column. Only populated for local tabular columns. The element will be an empty string otherwise.
- Example:
['STXT', 'POIN', 'DISC', '', ''] - Returns: List[str]
property column_histories
The revision histories of each column, as an ordered list of ObjectHistory objects.
- Returns:
List[
ObjectHistory]
property column_units
Unit symbols for each column.
- Returns: List[str]
property discrete_values
All possible discrete values, for all columns with the discrete data type.
- Returns: List[List[str]]
property column_targets
Column meta-types. Possible column targets are:
Local - Contains local data
TargetAttribute - Contains data from a linked attribute
TargetRecord - Contains the records that the rows link to
TargetTabularColumn - Contains data from a linked tabular column
Unavailable - Data cannot be viewed, usually due to version control or permissions
- Returns: List[str]
property columns
Column names (headers).
- Returns: List[str]
property columns_to_process
Columns to be included when populating an AttributeTabular object. Defaults to all
columns, which will fully populate the AttributeTabular object. Columns that aren’t processed contain the
value <Ignored>. Tabular attributes with <Ignored> columns can be imported back into Granta MI with no
loss of data (additional conditions exist for Picture and File columns, see Warning below).
Ignoring columns that aren’t required by the script can significantly improve performance for operations with large amounts of tabular data.
NOTE
This property must be set on the AttributeDefinitionTabular object associated with the Table object before data export for the setting to have an effect.
WARNING
If the intention is to export, modify, and update tabular data, and Table.bulk_fetch() is
being used for the initial export of data, it is recommended to call Table.bulk_fetch() with
include_binary_data = True.
If Table.bulk_fetch() is called with include_binary_data = False, Picture and File columns must
not be removed from the columns_to_process list or an exception will be raised when attempting to
re-import the tabular attribute.
It is possible to call Table.bulk_fetch() with include_binary_data = False as long as all Picture
and File columns are set to be processed, but this will have a performance impact. See the
Table.bulk_fetch() documentation for more details.
- Returns: List[str]
property ignore_linked_records
Whether to ignore linked records when creating Record objects. Defaults to False.
Even when set to True, linking values are still available if populated.
Ignoring linked records if they aren’t required can significantly improve performance for operations with large amounts of tabular data.
NOTE
This property must be set on the AttributeDefinitionTabular object associated with the Table object before data export for the setting to have an effect.
- Returns: bool
AttributeDefinitionUnsupported
class AttributeDefinitionUnsupported(table)
__init__(table)
Extended AttributeDefinition class for unsupported attribute types (maths
functional (equations and logic), discrete functional).
Provides access to the limited information available for unsupported attribute types (name, type and unit, if present).
- Parameters:
table –
Tableobject - Returns: None
PseudoAttributeDefinition
class PseudoAttributeDefinition(name)
__init__(name)
Stores basic information about a pseudo-attribute.
NOTE
Supported names are:
recordTyperecordHistoryIdentityrecordColorrecordVersionNumbertableNamewritableparentShortNameparentNameparentRecordHistoryIdentityshortNamemodifiedDatecreatedDatereleasedDatelastModifiercreatorsubsetsname
- Parameters: name – str
- Returns: None
property id
Attribute identifier (this is always 0 for pseudo-attributes).
- Returns: int
property read_only
Whether the current user has the correct permissions to edit the attribute.
- Returns: bool
property unit
Unit symbol for the pseudo-attribute.
- Returns: str
property name
Name of the pseudo-attribute.
- Returns: str
property type
Data type of the pseudo-attribute (four-character string).
- Returns: str
Attribute Values
These classes are attribute objects that contain data. There is (at least) one for each type.
- AttributeValue - Base class for all attributes
- AttributeBinary - Parent class for the binary attributes, AttributePicture and AttributeFile
- AttributePicture - Attribute value class covering picture data
- AttributeFile - Attribute value class covering file data
- AttributeDate - Attribute value class covering datetime data
- AttributeDiscrete - Attribute value class covering discrete data
- AttributeFunctional - Attribute value class covering functional data. This is subclassed by FunctionalSeries and FunctionalGrid.
- FunctionalSeries - Attribute value class covering float functional series data
- FunctionalGrid - Attribute value class covering float functional gridded data
- AttributeHyperlink - Attribute value class covering hyperlink data
- AttributeInteger - Attribute value class covering integer data
- AttributeLogical - Attribute value class covering logical data
- AttributePoint - Attribute value class covering point with parameter data
- AttributeRange - Attribute value class covering range data
- AttributeTabular - Attribute value class covering tabular data
- AttributeShortText - Attribute value class covering short text data
- AttributeLongText - Attribute value class covering long text data
- AttributeUnsupported - Attribute value class covering unsupported data
- PseudoAttributeValue - Pseudo-attribute value class covering all pseudo-attribute types
AttributeValue
class AttributeValue(attr_def, _gdl_av, _mi, record, metas=None)
Stores and provides access to attribute data values.
NOTE
Do not create new instances of this class; it represents a pre-existing database structure, and empty instances are provided when needed.
The attributes in a Record are represented in the MI Scripting Toolkit by
AttributeDefinition objects,
with an associated AttributeValue object containing the attribute’s data.
AttributeValue is the base class, and each attribute type has a specialised class that inherits from it.
NOTE
The ‘Notes’ meta-attribute, common to all attributes, is not accessible through the MI Scripting Toolkit.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclasses for each meta-attribute of this attribute)
- attr_def –
- Returns: None
property value
Current value of the attribute. Can be modified.
- Returns: Union[List[str], List[float], str, Dict[str, float], int, float, bool, bytes]
property record
Record in which the attribute value is defined. Would be None
if the AttributeValue has been created outside a Record context, e.g.
with Table.create_empty_attribute_value.
- Returns:
Recordobject or None
is_empty()
Checks whether the attribute value is populated.
- Returns: bool
property definition
AttributeDefinition associated with this AttributeValue.
- Returns:
AttributeDefinitionobject
property id
Attribute identifier.
- Returns: int
property is_meta
Whether the attribute is a meta-attribute.
- Returns: bool
property is_meta_for
Name of the parent attribute, if a meta-attribute. Returns None if not.
- Returns: str or None
property meta_attributes
Meta-attributes associated with this attribute. Does not make calls to the Service Layer.
- Returns:
Dict[str,
AttributeValue]
property name
Attribute name.
- Returns: str
property type
Attribute data type, as a four-character string. Possible attribute types are:
POIN = point,
RNGE = range,
FUNC = float functional,
INPT = integer,
LOGI = logical,
DISC = discrete,
STXT = short text,
LTXT = long text,
DTTM = date time,
HLNK = hyperlink,
PICT = picture,
FILE = file,
DSFN = discrete functional,
MAFN = maths functional (equations and logic),
TABL = tabular.
DSFN and MAFN are not supported by the MI Scripting Toolkit, and appear as UNSUPPORTED DATA TYPE.
- Returns: str
property unit
Unit symbol.
- Returns: str
property is_applicable
Whether the attribute is applicable to the current record. Setting this to False will clear
any data values on the attribute.
- Returns: bool
AttributeBinary
class AttributeBinary(attr_def, _gdl_av, _mi, record, metas=None, path=None, content_type=None)
Extended AttributeValue class to handle BinaryType objects
as attribute data values.
Provides access to BinaryType object methods and properties.
__init__(attr_def, _gdl_av, _mi, record, metas=None, path=None, content_type=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute) - path – str (Path to the file associated with the attribute)
- content_type – str (MIME content/file type; see
BinaryType)
- attr_def –
- Returns: None
property url
URL of the hosted file. Returns None if not populated.
The data can be retrieved by using a Python HTTP library (e.g. Requests, HTTPX) and by supplying the appropriate authentication for your Granta MI server.
To populate this property, the Table.bulk_fetch() method must be used with
include_binary_data = False (default). If include_binary_data = True is specified, or if the attribute
is fetched on-demand by accessing the attributes dictionary without performing a bulk fetch, this property
will always return None.
- Returns: str or None
property mime_file_type
MIME (Multipurpose Internet Mail Extensions) file type, if populated.
When exporting, this property is populated with the value of the MIME file type as determined by Granta MI.
When importing, this property is populated automatically by the load() method:
- For Picture attributes, the MIME file type is determined by the image data.
- For File attributes, this property is not used and is set to
None.
Some commonly-used extensions are:
image/png - .png
image/gif - .gif
image/bmp - .bmp
image/tiff - .tif, .tiff
text/plain - .txt
application/zip - .zip
application/pdf - .pdf
application/vnd.ms-excel - .xls
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - .xlsx
application/vnd.ms-powerpoint - .ppt
application/vnd.openxmlformats-officedocument.presentationml.presentation - .pptx
application/msword - .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document - .docx
- Returns: str
is_empty()
Checks if the BinaryType object is populated by checking if it contains any binary data.
- Returns: bool
property value
Returns the file as a bytes object, or None if unset.
- Returns: bytes or None.
AttributePicture
class AttributePicture(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeBinary class for handling Picture objects.
Provides access to Picture save/load methods.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
save(path)
Wraps the Picture.save() method.
- Parameters:
path (Union [str , pathlib.Path ]) – Path where the image should be saved.
Takes the form
C:\\Users\\yourname\\Pictures\\image.jpgor/home/username/Pictures/image.jpg. - Returns: None
load(path)
Wraps the Picture.load() method (populates the Picture object with the specified image file).
- Parameters:
path (Union [str , pathlib.Path ]) – Path to the image file to load.
Takes the form
C:\\Users\\yourname\\Pictures\\image.jpgor/home/username/Pictures/image.jpg. - Returns: None
AttributeFile
class AttributeFile(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeBinary class to handle File objects.
Provides access to File object save/load methods, file name, and description.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
save(path)
Wraps the File.save() method.
- Parameters:
path (Union [str , pathlib.Path ]) – Path where the file should be saved.
Takes the form
C:\\Users\\yourname\\Documents\\file.pdfor/home/username/Documents/file.pdf. - Returns: None
load(path)
Wraps the File.load() method (populates the File object with the specified file).
- Parameters:
path – Union[str, pathlib.Path] (Path to the file to be imported.
Takes the form
C:\\Users\\yourname\\Documents\\file.pdfor/home/username/Documents/file.pdf. - Returns: None
property file_name
Name of the file associated with the File object. Displayed in MI applications.
- Returns: str
property description
Description of the file displayed in MI applications.
- Returns: str
AttributeDate
class AttributeDate(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for date attributes.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
property value_as_string
Return the value of the date attribute as a string.
- Returns: str | None
property value
Return the value of the date attribute as a datetime.datetime object.
- Returns:
datetime.datetimeobject | None
AttributeDiscrete
class AttributeDiscrete(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for discrete attributes.
Provides access to the list of strings that store the attribute’s data values, and their display order.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
property value
Discrete value(s) associated with this attribute.
- Returns: List[str] or str if not multivalued
property order
Display order of the discrete data values (strings) in MI Viewer. Order cannot be edited using the MI Scripting Toolkit.
- Returns: List[int]
property is_multivalued
Whether this attribute allows multiple values to be set.
- Returns: bool
property possible_discrete_values
List of the attribute’s possible discrete data values.
- Returns: List[str]
AttributeFunctional
class AttributeFunctional(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for functional data attributes.
Stores and provides access to a data structure, parameters (constraints), specified x-axis, and individual
columns and series within the functional data attribute. Series and Gridded data are stored identically in
AttributeFunctional objects. However, the two data types are imported into MI differently.
The AttributeFunctional object data structure is as follows:
[[ 'y min', 'y max', 'constraint 1', 'constraint 2', 'Estimated point?'],
[ 0.0, 0.0, 'Test', 0.5, , False, ],
[ . , . , . , . , , . , ],
[ . , . , . , . , , . , ],
[ . , . , . , . , , . , ]]
The allowed data types are float for x-y data, float, str or None for constraints, and bool for
flagging whether the data point is estimated or not.
The functional data type is used to store graphical data in Granta MI. In MI Viewer there are two ways to view the data: Series and Gridded.
- Series data is grouped according to constraints or parameters placed on x-y data. The x-axis is a constraint that is specified on import. Each group (‘Series’) can have a different linestyle.
- Gridded data is similar to Series data, except that the x-axis is dynamically chosen within MI Viewer, and all data groups share one linestyle.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
update_header_units()
Updates the unit symbols in the header with the currently selected units.
- Returns: None
property unit
Unit symbol for the y-axis.
- Returns: str
clear()
Deletes all data stored in the AttributeFunctional object.
- Returns: None
is_empty()
Checks whether any of the data values in the attribute are populated.
- Returns: bool
add_point(columns)
Adds a point value to the AttributeFunctional object. Requires a dictionary with keys for the y-value,
each constraint, and whether the value is estimated (optional):
- Dictionary keys for the y-value can be either ‘y’, ‘Y’, the attribute name, or the attribute name prefixed
with ‘Y ‘ and suffixed with the unit symbol in square brackets, i.e. formatted as in
column_headers. - Constraint keys can be either the parameter name, or the parameter name with units.
- Constraints are optional and can either be omitted entirely or set to None.
- The key for whether the value is estimated must be ‘Estimated?’.
NOTE
The Estimated? flag can currently only be set for Gridded data, not Series.
- Parameters: columns – Dict[str, Union[str, float, bool, int]]
- Returns: None
add_range(columns)
Adds a range value to the AttributeFunctional object. Requires a dictionary with keys for the two
y-values (ymin and ymax), each constraint, and whether the value is estimated (optional).
- Dictionary keys for the y-value can be either ‘ymin’, ‘ymax’, or the attribute name with units and ‘Y min’ or ‘Y max’ appended.
- Constraint keys can either be the parameter name, or the parameter name with units.
- Constraints are optional and can either be omitted entirely or set to None.
- The key for whether the value is estimated must be ‘Estimated?’.
NOTE
The Estimated? flag can currently only be set for Gridded data, not Series.
- Parameters: columns – dict
- Returns: None
property xaxis_parameter
ParameterDefinition for the current x-axis parameter of the functional data attribute.
- Returns:
ParameterDefinitionobject
property column_headers
Column headers with units.
- Returns: List[str]
property constraint_column_index
Mapping of columns to indices for functional data attributes.
- Returns: Dict[str, int]
data_by_column()
Sorts data into columns (lists of values indexed by column name). Changing a dictionary generated using this method does not affect the underlying data, and data in the dictionary will not be refreshed automatically if the underlying data changes.
- Returns: Dict[str, List[Any]]
property parameters
Parameters used by the functional data attribute, indexed by name.
- Returns:
Dict[str,
ParameterDefinition]
FunctionalSeries
class FunctionalSeries(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeFunctional class for Series functional data attributes.
Provides access to Series numbers and linestyles, and a method of generating a FunctionalGrid object from a
FunctionalSeries object (generate_grid_version()).
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
generate_grid_version()
Creates a Gridded version of the FunctionalSeries object and returns a copy of it.
- Returns:
FunctionalGridobject
property data_with_series_number
Series number for all data points, returned as an additional column with the data values.
- Returns: List[List[Union[str, float, bool, int]]]
property series_linestyles
Linestyles for each series (linestyle can be ‘Lines’, ‘Markers’, or ‘Both’).
- Returns: Dict[int, str]
property log_yaxis
Whether the Y axis is using a logarithmic scale.
- Returns: bool
FunctionalGrid
class FunctionalGrid(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeFunctional class for Gridded functional data attributes.
Provides access to linestyle and a method of generating a FunctionalSeries object from a
FunctionalGrid object (generate_series_version()).
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
generate_series_version()
Creates a Series version of the FunctionalGrid object and returns a copy of it.
- Returns:
FunctionalSeriesobject
property linestyle
Linestyle for gridded functional data (gridded data can only have one linestyle: ‘Lines’, ‘Markers’, or ‘Both’).
- Returns: str
AttributeHyperlink
class AttributeHyperlink(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for hyperlink attributes.
Provides access to the hyperlink_description and hyperlink_display text properties.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
property object
Hyperlink attribute object value.
- Returns:
Hyperlink
property value
Returns the URL as a string, or None if unset.
- Returns:
str or
None.
property hyperlink_display
Indicates how the hyperlink should be opened when clicked on in MI applications. Takes one of the following values:
New: Open in a new window or tab.Top: Open in the current window or tab.Content: Open within the current MI application (for example, in a frame or dialog).
property hyperlink_description
Text which displays instead of the URL in MI applications.
- Returns: str
AttributeInteger
class AttributeInteger(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for integer attributes.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
property value
Current value of the attribute. Can be modified.
- Returns: Union[List[str], List[float], str, Dict[str, float], int, float, bool, bytes]
AttributeLogical
class AttributeLogical(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for logical attributes.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
AttributePoint
class AttributePoint(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for point data attributes.
Provides access to lists of point values and their parameters. Points can be multi-valued and are represented in the Streamlined API as lists of floats. They can have multiple parameters.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
property is_multivalued
Whether this attribute allows multiple values to be set.
- Returns: bool
is_empty()
Checks whether the attribute value is populated. AttributePoint objects are empty if the length
of the list AttributePoint.value == 0.
- Returns: bool
property is_estimated
Whether the value has been estimated.
Defaults to False for new attribute values.
return: bool
property parameter_definitions
Parameter definitions for the parameters associated with the point attribute, indexed by name.
- Returns:
Dict[str,
ParameterDefinition]
property parameters
Parameters associated with each point in AttributePoint.value. Each point has a
dictionary, indexed by parameter name and containing the parameter value for that point.
- Returns: List[Dict[str, Union[float, str]]]
property value
Point values associated with this attribute.
- Returns: Union[List[float], float]
AttributeRange
class AttributeRange(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for range data attributes. Range attribute values are represented in
the MI Scripting Toolkit by dictionaries of the form {'low': float, 'high': float}, and should be entered
in this form when editing them.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
property value
Current value of the attribute. Can be modified.
- Returns: Union[List[str], List[float], str, Dict[str, float], int, float, bool, bytes]
property is_estimated
Whether the value has been estimated.
Defaults to False for new attribute values.
return: bool
property high_value_is_inclusive
Whether the high value is included in the range.
Defaults to True for new attribute values.
return: bool
property low_value_is_inclusive
Whether the low value is included in the range.
Defaults to True for new attribute values.
return: bool
AttributeTabular
class AttributeTabular(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for tabular data attributes.
Provides access to tabular data and its properties, such as linking attribute and table, and methods for adding, deleting or swapping rows.
WARNING
Importing an empty tabular attribute is deprecated. To delete all rows in an existing tabular attribute,
use the Record.clear_attributes method to delete the attribute value. To mark the attribute
as Not Applicable, set the AttributeValue.is_applicable property to False.
Use the AttributeTabular.shape property to determine the current number of rows in the
tabular attribute.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
property columns
List of columns in the tabular data.
- Returns: List[str]
property column_types
Data type in each column. Only populated for local, linked attribute, or linked column tabular columns. The element will be an empty string otherwise.
- Example:
['STXT', 'POIN', 'DISC', '', ''] - Returns: List[str]
property linked_columns
Whether each column is linked or not.
- Returns: List[bool]
property linking_table
Table object which the linking attribute belongs to. Returns None for purely local tabular data.
- Returns:
Tableobject or None
property linking_attribute
Linking attribute, a short text-type attribute used to link rows in the tabular data attribute to records.
Returns None for purely local tabular data.
- Returns:
AttributeDefinitionobject or None
property value
Raw data for the attribute (list of data values per column).
property units
TabularUnits object associated with this AttributeTabular object.
- Returns:
TabularUnitsobject
show()
Displays the data as an ascii-art style table.
- Returns: None
load()
Loads linked tabular data into the class.
- Returns: None
property linked_records
The records linked to each row, indexed by the linking value of each row at loading.
These links are calculated in Granta MI, and therefore cannot be edited by the user. The dictionary is unaffected by local changes to the tabular data, and the data must be re-imported to reflect local changes.
This property will be empty if the user cannot access the linked table, or if
AttributeDefinitionTabular.ignore_linked_records was set to True before data export.
- Returns:
Dict[str, List[
Record]]
is_empty()
Checks whether the attribute value is populated.
- Returns: bool
property shape
Number of columns by number of rows.
- Returns: Tuple[int, int]
add_row(linking_value='')
Inserts a new unpopulated row, and sets the linking value for that row if one is provided.
- Parameters: linking_value – str
- Returns: None
delete_row(index)
Removes the row at the specified index.
- Example:
delete_row(0)deletes the first row. - Parameters: index – int
- Returns: None
swap_rows(row1, row2)
Change the positions of two rows with indices row1 and row2.
- Example:
my_data.swap_rows(0, 4)swaps the first and fifth rows in the Tabular data structuremy_data. - Parameters:
- row1 – int
- row2 – int
- Returns: None
AttributeShortText
class AttributeShortText(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for short text attributes.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
property value
Current value of the attribute. Can be modified.
- Returns: Union[List[str], List[float], str, Dict[str, float], int, float, bool, bytes]
AttributeLongText
class AttributeLongText(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for long text attributes.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
AttributeUnsupported
class AttributeUnsupported(attr_def, _gdl_av, _mi, record, metas=None)
Extended AttributeValue class for attributes with unsupported data types.
Note that unsupported attribute data will not yield any information regarding its value in that record. However, some meta-data is still available through this class (such as the attribute’s name and data type). An unsupported attribute value remains unpopulated, and these objects cannot be edited.
__init__(attr_def, _gdl_av, _mi, record, metas=None)
- Parameters:
- attr_def –
AttributeDefinitionobject - _gdl_av – Foundation API
GRANTA_MIScriptingToolkit.AttributeValueclass for this attribute - _mi –
Sessionobject - record – Parent
Recordobject - metas – List[
GRANTA_MIScriptingToolkit.AttributeValue] (Foundation APIGRANTA_MIScriptingToolkit.AttributeValueclass for each meta-attribute of this attribute)
- attr_def –
- Returns: None
property object
Gets the underlying UnsupportedType object representing the attribute value or the tabular cell. Does
not allow access to the data.
property is_applicable
Whether the attribute is applicable to the current record. Setting this to False will clear
any data values on the attribute.
- Returns: bool
is_empty()
Checks whether the attribute value is populated.
- Returns: bool
PseudoAttributeValue
class PseudoAttributeValue(name, record)
Stores and provides access to pseudo-attribute data values.
__init__(name, record)
- Parameters:
- name – str
- record – Parent
Record
- Returns: None
property record
Parent Record described by the PseudoAttributeValue
- Returns:
Recordobject
property value
Current value of the pseudo-attribute. Cannot be modified. Modification of pseudo-attributes must be done
through the Record object properties color, short_name and name.
- Returns:
Union[List[str], str, int, bool, Set[str],
datetime.datetime,RecordColor]
property id
Attribute identifier (this is always 0 for pseudo-attributes).
- Returns: int
is_empty()
Checks whether the pseudo-attribute value is populated or not.
- Returns: bool
property name
Name of the pseudo-attribute.
- Returns: str
property type
Data type of the pseudo-attribute value (four-character string).
- Returns: str
Sub-attribute level
Classes that are used by attribute objects but are not attributes themselves.
ParameterDefinition
class ParameterDefinition(_gdl_param, _mi, unit_conversions=None)
__init__(_gdl_param, _mi, unit_conversions=None)
Streamlined API wrapper for the Foundation API GRANTA_MIScriptingToolkit.ParameterDetail class.
Provides access to parameter properties such as revision history, default and possible values, and units.
NOTE
Do not create new instances of this class; it represents a pre-existing database structure.
- Parameters:
- _gdl_param – Foundation API
GRANTA_MIScriptingToolkit.ParameterDetailclass - _mi –
Sessionobject - unit_conversions – Dict[str, str] (maps database units to the current unit system’s units)
- _gdl_param – Foundation API
- Returns: None
property value_for_exporters
Value on the ParameterDefinition instance for use in any exporters the parameter is passed to. Can be set
by the user.
If this value is unset, the exporter will use the default value defined in Granta MI.
- Returns: Union[str, float]
property name
Parameter name.
- Returns: str
property parent_attribute
Name of the parent attribute.
- Returns: str
property parent_record
Long name of the parent record.
- Returns: str
property history
Revision history of the parameter, as an ObjectHistory object.
- Returns:
ObjectHistoryobject
property default_value
Default value of the parameter (all parameters must have a default value).
- Returns: str or float
property history_of_default
Revision history of the parameter’s default value, as an ObjectHistory object.
- Returns:
ObjectHistoryobject
property interpolation_type
The interpolation type for the parameter (‘None’, ‘Linear’, or ‘Cubic Spline’).
- Returns: str
property order
Order in which the parameter is stored in the attribute (column number). This is relevant for some interpolation methods, and determines the display order in MI Viewer.
- Returns: int
property axis_scale_type
Axis scale type for the parameter (‘Linear’ or ‘Logarithmic’).
- Returns: str
property unit
Unit symbol for the parameter.
- Returns: str
reset_unit()
Resets the unit back to its original value (the unit in use when the parameter was initially exported). Does not make a call to the Service Layer.
- Returns: None
property values
List of all possible values the parameter can take.
- Returns: List[Union[str, float]]
property values_histories
Revision histories of each possible value of a parameter, as a list of ObjectHistory objects.
- Returns:
List[
ObjectHistory]
property type
Parameter type (‘Unrestricted’ numeric, ‘Restricted’ numeric, or ‘Discrete’).
- Returns: str
property id
Parameter identifier.
- Returns: int
ObjectHistory
class ObjectHistory(_gdl_revision_info)
Provides access to the revision history of an MI database element. Object histories are currently supported via the following properties:
NOTE
Do not create new instances of this class; it represents a pre-existing database structure.
__init__(_gdl_revision_info)
- Parameters:
_gdl_revision_info – Foundation API
GRANTA_MIScriptingToolkit.RevisionInfoclass - Returns: None
property last_modified_date
Date the database element was last modified.
- Returns: str
property last_modified_at
Date and time the database element was last modified.
- Returns: datetime.datetime
property date_created
Date the database element was created.
- Returns: str
property created_at
Date and time the database element was created.
- Returns: datetime.datetime
property last_modified_by
The username of the last user to modify the database element.
- Returns: str
property created_by
The username of the user who created the database element.
- Returns: str
property update_count
The number of times the object has been updated.
- Returns: str
RecordVersionHistory
class RecordVersionHistory(record_version_state)
Provides access to the revision history of an MI Record.
NOTE
Do not create new instances of this class; it represents a pre-existing database structure.
__init__(record_version_state)
property created_at
Date and time the record version was created.
- Returns: datetime.datetime
property created_by
The username of the user who created the record version.
- Returns: str
property creation_notes
Notes associated with the creation of the record version.
- Returns: str
property last_modified_at
Date and time the record version was last modified.
- Returns: datetime.datetime
property last_modified_by
The username of the user who last modified the record version.
- Returns: str
property last_modification_notes
Notes associated with the last modification made to record version.
- Returns: str
property released_at
Date and time the record version was released.
- Returns: datetime.datetime
property released_by
The username of the user who released the record version.
- Returns: str
property release_notes
Notes associated with the release of the record version.
- Returns: str
property superseded_at
Date and time the record version was superseded.
- Returns: datetime.datetime
property superseded_by
The username of the user who superseded the record version.
- Returns: str
property supersession_notes
Notes associated with the last operation that superseded the record version.
- Returns: str
property withdrawn_at
Date and time the record version was withdrawn.
- Returns: datetime.datetime
property withdrawn_by
The username of the user who withdrew the record version.
- Returns: str
property withdrawal_notes
Notes associated with the withdrawal of the record version.
- Returns: str
DataRevisionHistory
class DataRevisionHistory(record_attribute)
Provides revision history information about the data in an attribute of a record.
NOTE
Do not create new instances of this class; it represents a pre-existing database structure.
__init__(record_attribute)
property name
Name of the attribute.
- Returns: str
property is_populated
Whether the attribute is populated.
- Returns: bool
property created_in_record_version
Version of the record when this datum was created.
- Returns: int
property retired_in_record_version
Version of the record when this datum was retired.
- Returns: int
property data_version_number
Data version number.
- Returns: int
property history
Revision history of the attribute data, as an ObjectHistory object. Is None for empty attributes.
- Returns:
ObjectHistoryobject or None
property meta_attributes
Data revision history of meta-attributes associated with this attribute, indexed by meta-attribute name.
- Returns:
Dict[str,
DataRevisionHistory]
property is_meta_for
Name of the parent attribute, if a meta-attribute. Returns None otherwise.
- Returns: str or None
property is_meta
Whether the attribute is a meta-attribute or not.
- Returns: bool
SearchCriterion
class SearchCriterion(attribute, operator, value=None, column_name=None)
Defines a single criterion for use in a search. The criterion can be as simple as the presence of the
specified attribute, or as complex as the data in a specified column of the tabular attribute being
greater than a specified value. The search will use the same units as the
AttributeDefinition.
__init__(attribute, operator, value=None, column_name=None)
- Parameters:
- attribute –
AttributeDefinitionobject - operator – str
- value – Input type corresponding to your
AttributeDefinition - column_name – str
- attribute –
NOTE
To perform an exact search on a discrete attribute, the operator argument should be
either CONTAINS_ANY or CONTAINS_ALL. In the case of searching for a single discrete
value, the value argument should be a list containing the search term.
- Returns: None
property attribute
AttributeDefinition for the attribute used in this search criterion.
- Returns:
AttributeDefinitionobject
property operation
Operator used in this criterion, if provided.
- Example: ‘EXISTS’ or ‘CONTAINS’
- Returns: str
Hyperlink
class Hyperlink(url=None, hyperlink_display='New', hyperlink_description='')
Represents hyperlinks in MI. Can be used directly in tabular data, or within AttributeHyperlink objects for
standalone hyperlink attributes.
__init__(url=None, hyperlink_display='New', hyperlink_description='')
- Parameters:
- url – str
- hyperlink_display – str (Hyperlink display mode:
New,Content,Top) - hyperlink_description – str (Hyperlink description, displayed in MI applications)
- Returns: None
property hyperlink_display
Indicates how the hyperlink should be opened when clicked on in MI applications. Takes one of the following values:
-
New: Open in a new window or tab. -
Top: Open in the current window or tab. -
Content: Open within the current MI application (for example, in a frame or dialog). -
Returns: str
BinaryType
class BinaryType
Stores and provides access to Pictures and Files, and associated metadata. Pictures and files can appear in Granta MI as data (for example, in a tabular data column), or as an attribute value.
The BinaryType object wraps files and images for inclusion in the corresponding MI Scripting Toolkit
classes.
__init__()
- Returns: None
property value
Current value of the attribute; BinaryType.value always returns the current instance of the class
and cannot be modified. In this case, the values are the file or picture, which can be accessed through
the load and save methods of the File or Picture classes.
- Returns:
BinaryTypeobject
property url
URL of the hosted file. Returns None if not populated.
The data can be retrieved by using a Python HTTP library (e.g. Requests, HTTPX) and by supplying the appropriate authentication for your Granta MI server.
To populate this property, the Table.bulk_fetch() method must be used with
include_binary_data = False (default). If include_binary_data = True is specified, or if the attribute
is fetched on-demand by accessing the attributes dictionary without performing a bulk fetch, this property
will always return None.
- Returns: str or None
property mime_file_type
MIME (Multipurpose Internet Mail Extensions) file type.
When exporting, this property is populated with the value of the MIME file type as determined by Granta MI.
When importing, this property is populated automatically by the load() method:
- For Picture attributes, the MIME file type is determined by the image data.
- For File attributes, this property is not used and is set to
None.
Some commonly-used extensions are:
image/png - .png
image/gif - .gif
image/bmp - .bmp
image/tiff - .tif, .tiff
text/plain - .txt
application/zip - .zip
application/pdf - .pdf
application/vnd.ms-excel - .xls
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - .xlsx
application/vnd.ms-powerpoint - .ppt
application/vnd.openxmlformats-officedocument.presentationml.presentation - .pptx
application/msword - .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document - .docx
- Returns: str
is_empty()
Checks whether the BinaryType object is populated by checking whether there is binary data in the object.
- Returns: bool
property binary_data
The binary data for the file. Binary data can be set with a bytes object or file buffer.
- Returns: bytes or None.
Picture
class Picture(*, path=None)
Extended BinaryType class for Pictures in MI.
__init__(*, path=None)
- Parameters:
path (Optional *[*Union [str , pathlib.Path ] ]) – Path to the image file to load. Takes the form
C:\\Users\\username\\Pictures\\image.jpgor/home/username/Pictures/image.jpg. - Returns: None
load(path)
Populates the Picture object with the image located on path. Relative paths are permitted.
- Parameters:
path (Union [str , pathlib.Path ]) – Path to the image file to load. Takes the form
C:\\Users\\username\\Pictures\\image.jpgor/home/username/Pictures/image.jpg. - Returns: None
save(path)
Saves a Picture object to file location path. Relative paths are permitted.
- Parameters:
path (Union [str , pathlib.Path ]) – Path where the image should be saved. Takes the form
C:\\Users\\username\\Pictures\\image.jpgor/home/username/Pictures/image.jpg. - Returns: None
property binary_data
The binary data for the file. Binary data can be set with a bytes object or file buffer.
- Returns: bytes or None.
File
class File(*, path=None)
Extended BinaryType class for Files in MI.
__init__(*, path=None)
- Parameters:
path (Optional *[*Union [str , pathlib.Path ] ]) – Path to the file to load. Takes the form
C:\\Users\\username\\Documents\\file.pdfor/home/username/Documents/file.pdf. - Returns: None
save(path)
Saves a File object to file location path. Relative paths are permitted.
- Parameters:
path (Union [str , pathlib.Path ]) – Path where the file should be saved. Takes the form
C:\\Users\\username\\Documents\\file.pdfor/home/username/Documents/file.pdf. - Returns: None
load(path)
Populates the File object with the file located by path. Relative paths are permitted.
- Parameters:
path (Union [str , pathlib.Path ]) – Path to the file to load. Takes the form
C:\\Users\\username\\Documents\\file.pdfor/home/username/Documents/file.pdf. - Returns: None
property file_name
Name of the file.
- Returns: str
property description
File description.
Stored with the data value. If provided, the description replaces the file name for the attribute when displayed on a datasheet in MI Viewer.
- Returns: str
UnsupportedType
class UnsupportedType(_gdl_av)
Represents a data type that is unsupported. No information about the value of the Attribute or the Tabular Cell is available. However, the object’s data type is available through this class, along with the underlying gdl object, which may contain more information. Properties of this object cannot be edited.
__init__(_gdl_av)
TabularUnits
class TabularUnits(units, default_units, database_units)
Stores and provides access to the units for a parent AttributeTabular object, in the same tabular format as
the data.
Units can be set on a cell-by-cell basis. TabularUnits is populated when the parent
AttributeTabular object is loaded.
Any changes made to the underlying AttributeTabular.value() property must also be made to the corresponding
TabularUnits.data() and vice versa, or your changes will not import successfully and may be lost
(AttributeTabular.add_row() and AttributeTabular.delete_row() make the necessary changes to both
objects, but you must duplicate other changes to data yourself).
__init__(units, default_units, database_units)
- Parameters:
- units – List[List[str]]
- default_units – List[str] the default units applied when creating new rows for each column
- database_units – List[str] the units defined in the database for each column
- Returns: None
property database_units
The database units, as a list corresponding to each column.
- Returns: List[str]
property default_units
The default units, as a list corresponding to each column.
- Returns: List[str]
property data
Data values (unit symbol strings) stored in the TabularUnits object.
- Returns: List[List[str]]
Helper Functions
connect
connect(service_layer_url, user_name=None, password=None, domain=None, autologon=None, timeout=300000, existing_session=None, oidc=False, auth_token=None, refresh_token=None, use_stored_token=False, store_password=False, max_retries=0)
Establishes a connection to the Granta MI server and returns a Session object.
An existing session may be specified.
- Parameters:
- service_layer_url – str
- user_name – str
- password – str
- domain – str
- autologon – bool
- timeout – int (maximum time to wait for a response, in milliseconds)
- existing_session – Foundation API
GRANTA_MIScriptingToolkit.GRANTA_MISessionclass - oidc – bool
- auth_token – str
- refresh_token – str
- use_stored_token – bool
- store_password – bool (Default value False. Set to True when the password is given and needs to be saved for the session’s duration, for example when parallelisation is required.)
- max_retries – int (Default value 0. Maximum number of times to retry requests sent to the Service Layer.)
- Returns:
Sessionobject
NOTE
If MI Scripting Toolkit has been installed on the same server machine as Granta MI, then the Granta MI server name must be specified in full in the url parameter. If you use ‘localhost’ or a loopback address, MI Scripting Toolkit will be unable to use the specified user account to connect to Granta MI.
extract_parameter_value
extract_parameter_value(param_value)
Returns the data value stored in a Foundation API GRANTA_MIScriptingToolkit.ParameterValue object.
- Parameters:
param_value – Foundation API
GRANTA_MIScriptingToolkit.ParameterValueclass - Returns: str or float
get_foundation_logger
get_foundation_logger()
Return the logger used by the Foundation API (has the name “GDL”).
- Returns:
logging.Loggerclass
log_to_file_in_local_app_data
log_to_file_in_local_app_data(path='Granta Design\\MIScriptingToolkit\\Python')
Set up the built-in Granta logger to log to a file in the user’s local app data directory (%LOCALAPPDATA% on Windows, ‘~/.appdata/’ on Linux). The log file name is MIScriptingToolkitForPython_YYYY.MM.DD.log and you can specify the filepath. The default filepath is Granta Design/MIScriptingToolkit/Python.
- Parameters: path – str
- Returns: None
Constants
RecordProperties
class RecordProperties
Provides PseudoAttributeDefinition for every supported pseudo-attribute.
Attribute names match the corresponding property on Record.
name = <PseudoAttributeDefinition name: name, type: STXT>
short_name = <PseudoAttributeDefinition name: shortName, type: STXT>
subsets = <PseudoAttributeDefinition name: subsets, type: DISC>
type = <PseudoAttributeDefinition name: recordType, type: STXT>
history_identity = <PseudoAttributeDefinition name: recordHistoryIdentity, type: INPT>
color = <PseudoAttributeDefinition name: recordColor, type: STXT>
version_number = <PseudoAttributeDefinition name: recordVersionNumber, type: INPT>
table_name = <PseudoAttributeDefinition name: tableName, type: STXT>
is_writable = <PseudoAttributeDefinition name: writable, type: LOGI>
parent_record_short_name = <PseudoAttributeDefinition name: parentShortName, type: STXT>
parent_record_name = <PseudoAttributeDefinition name: parentName, type: STXT>
parent_record_history_identity = <PseudoAttributeDefinition name: parentRecordHistoryIdentity, type: INPT>
released_on = <PseudoAttributeDefinition name: releasedDate, type: TIDT>
last_modified_on = <PseudoAttributeDefinition name: modifiedDate, type: TIDT>
created_on = <PseudoAttributeDefinition name: createdDate, type: TIDT>
last_modified_by = <PseudoAttributeDefinition name: lastModifier, type: STXT>
created_by = <PseudoAttributeDefinition name: creator, type: STXT>
classmethod all()
All pseudo-attribute definitions.
- Return type: List[PseudoAttributeDefinition]
RecordColor
enum RecordColor(value)
Valid values are as follows:
Red = RecordColor.Red
Maroon = RecordColor.Maroon
Fuchsia = RecordColor.Fuchsia
Yellow = RecordColor.Yellow
Black = RecordColor.Black
Gray = RecordColor.Gray
Aqua = RecordColor.Aqua
Green = RecordColor.Green
Navy = RecordColor.Navy
Purple = RecordColor.Purple
Blue = RecordColor.Blue
Silver = RecordColor.Silver
Lime = RecordColor.Lime
Olive = RecordColor.Olive
Teal = RecordColor.Teal
White = RecordColor.White
InheritFromParent = RecordColor.InheritFromParent
RecordType
enum RecordType(value)
- Member Type:
str
Valid values are as follows:
Record = RecordType.Record
Folder = RecordType.Folder
Generic = RecordType.Generic
DATABASE_UNIT_SYSTEM
DATABASE_UNIT_SYSTEM
Value used to refer to the ‘Database unit system’.
Exceptions
class UnsupportedLinkGroupError
Exception raised when an operation is performed on a record link group which is incompatible with that operation.