Coretex
coretex.coretex.experiment.experiment.Experiment Class Reference
Inheritance diagram for coretex.coretex.experiment.experiment.Experiment:
coretex.coretex.experiment.executing_experiment.ExecutingExperiment

Public Member Functions

Dict[str, Any] parameters (self)
 
str projectPath (self)
 
bool updateStatus (self, ExperimentStatus status, Optional[str] message=None, bool notifyServer=True)
 
List[Metric] createMetrics (self, List[Tuple[str, str, MetricType, str, MetricType]] values)
 
bool submitMetrics (self, Dict[str, Tuple[float, float]] metricValues)
 
bool downloadProject (self)
 
Optional[ArtifactcreateArtifact (self, str localFilePath, str remoteFilePath, Optional[str] mimeType=None)
 
Self startCustomExperiment (cls, int projectId, Union[int, str] nodeId, Optional[str] name, Optional[str] description=None, Optional[List[Dict[str, Any]]] parameters=None)
 

Detailed Description

    Represents experiment entity from Coretex.ai

    Properties
    ----------
    datasetId : int
        id of dataset
    name : str
        name of Experiment
    description : str
        description of Experiment
    meta : Dict[str, Any]
        meta data of Experiment
    status : ExperimentStatus
        status of Experiment
    spaceId : int
        id of Coretex Space
    spaceName : str
        name of Coretex Space
    spaceTask : SpaceTask
        appropriate space task
    projectId : int
        id of project
    projectName : str
        name of project
    createdById : str
        id of created experiment
    useCachedEnv : bool
        if True chached env will be used, otherwise new environment will be created

Definition at line 38 of file experiment.py.

Member Function Documentation

◆ createArtifact()

Optional[Artifact] coretex.coretex.experiment.experiment.Experiment.createArtifact (   self,
str  localFilePath,
str  remoteFilePath,
Optional[str]   mimeType = None 
)
    Creates Artifact for the current Experiment on Coretex.ai

    Parameters
    ----------
    localFilePath : str
local path of Artifact file
    remoteFilePath : str
path of Artifact file on Coretex
    mimeType : Optional[str]
mimeType (not required) if not passed guesMimeType() function is used

    Returns
    -------
    Optional[Artifact] -> if response is True returns Artifact object, None otherwise

Definition at line 327 of file experiment.py.

327  def createArtifact(self, localFilePath: str, remoteFilePath: str, mimeType: Optional[str] = None) -> Optional[Artifact]:
328  """
329  Creates Artifact for the current Experiment on Coretex.ai
330 
331  Parameters
332  ----------
333  localFilePath : str
334  local path of Artifact file
335  remoteFilePath : str
336  path of Artifact file on Coretex
337  mimeType : Optional[str]
338  mimeType (not required) if not passed guesMimeType() function is used
339 
340  Returns
341  -------
342  Optional[Artifact] -> if response is True returns Artifact object, None otherwise
343  """
344 
345  return Artifact.create(self.id, localFilePath, remoteFilePath, mimeType)
346 

◆ createMetrics()

List[Metric] coretex.coretex.experiment.experiment.Experiment.createMetrics (   self,
List[Tuple[str, str, MetricType, str, MetricType]]  values 
)
    Creates specified metrics for the experiment

    Parameters
    ----------
    values : List[Tuple[str, str, MetricType, str, MetricType]]
Metric meta in this format ("name", "x_label", "x_type", "y_label", "y_type")

    Returns
    -------
    List[Metric] -> List of Metric objects

    Example
    -------
    >>> from coretex import ExecutingExperiment, MetricType
    \b
    >>> metrics = ExecutingExperiment.current().createMetrics([
    ("loss", "epoch", MetricType.int, "value", MetricType.float),
    ("accuracy", "epoch", MetricType.int, "value", MetricType.float)
])
    >>> if len(metrics) == 0:
    print("Failed to create metrics")

Definition at line 210 of file experiment.py.

210  def createMetrics(self, values: List[Tuple[str, str, MetricType, str, MetricType]]) -> List[Metric]:
211  """
212  Creates specified metrics for the experiment
213 
214  Parameters
215  ----------
216  values : List[Tuple[str, str, MetricType, str, MetricType]]
217  Metric meta in this format ("name", "x_label", "x_type", "y_label", "y_type")
218 
219  Returns
220  -------
221  List[Metric] -> List of Metric objects
222 
223  Example
224  -------
225  >>> from coretex import ExecutingExperiment, MetricType
226  \b
227  >>> metrics = ExecutingExperiment.current().createMetrics([
228  ("loss", "epoch", MetricType.int, "value", MetricType.float),
229  ("accuracy", "epoch", MetricType.int, "value", MetricType.float)
230  ])
231  >>> if len(metrics) == 0:
232  print("Failed to create metrics")
233  """
234 
235  if not Metric.createMetrics(self.id, values):
236  logging.getLogger("coretexpylib").info(">> [Coretex] Failed to create metrics!")
237  return []
238 
239  metrics: List[Metric] = []
240  for name, xLabel, xType, yLabel, yType in values:
241  clazz = getClassForMetric(name)
242 
243  if clazz is not None:
244  metric = clazz.create(name, xLabel, xType, yLabel, yType)
245  metrics.append(metric)
246 
247  else:
248  metric = Metric.create(name, xLabel, xType, yLabel, yType)
249  metrics.append(metric)
250 
251  self.metrics.extend(metrics)
252 
253  return self.metrics
254 
255 

◆ downloadProject()

bool coretex.coretex.experiment.experiment.Experiment.downloadProject (   self)
    Downloads project snapshot linked to the experiment

    Returns
    -------
    bool -> True if project downloaded successfully, False if project download has failed

Definition at line 300 of file experiment.py.

300  def downloadProject(self) -> bool:
301  """
302  Downloads project snapshot linked to the experiment
303 
304  Returns
305  -------
306  bool -> True if project downloaded successfully, False if project download has failed
307  """
308 
309  zipFilePath = f"{self.projectPath}.zip"
310 
311  response = networkManager.genericDownload(
312  endpoint=f"workspace/download?model_queue_id={self.id}",
313  destination=zipFilePath
314  )
315 
316  with ZipFile(zipFilePath) as zipFile:
317  zipFile.extractall(self.projectPath)
318 
319  # remove zip file after extract
320  os.unlink(zipFilePath)
321 
322  if response.hasFailed():
323  logging.getLogger("coretexpylib").info(">> [Coretex] Project download has failed")
324 
325  return not response.hasFailed()
326 

◆ parameters()

Dict[str, Any] coretex.coretex.experiment.experiment.Experiment.parameters (   self)
    Returns
    -------
    Dict[str, Any] -> Parameters for Experiment

Definition at line 95 of file experiment.py.

95  def parameters(self) -> Dict[str, Any]:
96  """
97  Returns
98  -------
99  Dict[str, Any] -> Parameters for Experiment
100  """
101 
102  return self.__parameters
103 

◆ projectPath()

str coretex.coretex.experiment.experiment.Experiment.projectPath (   self)
    Returns
    -------
    str -> Path for Experiment

Definition at line 105 of file experiment.py.

105  def projectPath(self) -> str:
106  """
107  Returns
108  -------
109  str -> Path for Experiment
110  """
111 
112  return FolderManager.instance().getTempFolder(str(self.id))
113 

◆ startCustomExperiment()

Self coretex.coretex.experiment.experiment.Experiment.startCustomExperiment (   cls,
int  projectId,
Union[int, str]  nodeId,
Optional[str]  name,
Optional[str]   description = None,
Optional[List[Dict[str, Any]]]   parameters = None 
)
    Starts an Experiment on Coretex.ai with the provided parameters

    Parameters
    ----------
    datasetId : int
id of dataset that is being used for starting custom Experiment
    projectId : int
id of project that is being used for starting custom Experiment
    nodeId : Union[int, str]
id of node that is being used for starting custom Experiment
    name : Optional[str]
name of Experiment
    description : Optional[str]
Experiment description (not required)
    parameters : Optional[List[Dict[str, Any]]]
list of parameters (not required)

    Returns
    -------
    Self -> Experiment object

    Raises
    ------
    NetworkRequestError -> if the request failed

    Example
    -------
    >>> from coretex import Experiment
    >>> from coretex.networking import NetworkRequestError
    \b
    >>> parameters = [
    {
        "name": "dataset",
        "description": "Dataset id that is used for fetching dataset from coretex.",
        "value": null,
        "data_type": "dataset",
        "required": true
    }
]
    \b
    >>> try:
    experiment = Experiment.startCustomExperiment(
        projectId = 1023,
        nodeId = 23,
        name = "Dummy Custom Experiment
        description = "Dummy description",
        parameters = parameters
    )

    print(f"Created experiment with name: {experiment.name}")
    >>> except NetworkRequestError:
    print("Failed to create experiment")

Definition at line 379 of file experiment.py.

379  def startCustomExperiment(
380  cls,
381  projectId: int,
382  nodeId: Union[int, str],
383  name: Optional[str],
384  description: Optional[str] = None,
385  parameters: Optional[List[Dict[str, Any]]] = None
386  ) -> Self:
387  """
388  Starts an Experiment on Coretex.ai with the provided parameters
389 
390  Parameters
391  ----------
392  datasetId : int
393  id of dataset that is being used for starting custom Experiment
394  projectId : int
395  id of project that is being used for starting custom Experiment
396  nodeId : Union[int, str]
397  id of node that is being used for starting custom Experiment
398  name : Optional[str]
399  name of Experiment
400  description : Optional[str]
401  Experiment description (not required)
402  parameters : Optional[List[Dict[str, Any]]]
403  list of parameters (not required)
404 
405  Returns
406  -------
407  Self -> Experiment object
408 
409  Raises
410  ------
411  NetworkRequestError -> if the request failed
412 
413  Example
414  -------
415  >>> from coretex import Experiment
416  >>> from coretex.networking import NetworkRequestError
417  \b
418  >>> parameters = [
419  {
420  "name": "dataset",
421  "description": "Dataset id that is used for fetching dataset from coretex.",
422  "value": null,
423  "data_type": "dataset",
424  "required": true
425  }
426  ]
427  \b
428  >>> try:
429  experiment = Experiment.startCustomExperiment(
430  projectId = 1023,
431  nodeId = 23,
432  name = "Dummy Custom Experiment
433  description = "Dummy description",
434  parameters = parameters
435  )
436 
437  print(f"Created experiment with name: {experiment.name}")
438  >>> except NetworkRequestError:
439  print("Failed to create experiment")
440  """
441 
442  if isinstance(nodeId, int):
443  nodeId = str(nodeId)
444 
445  if parameters is None:
446  parameters = []
447 
448  response = networkManager.genericJSONRequest(
449  f"{cls._endpoint()}/custom",
450  RequestType.post,
451  parameters={
452  "sub_project_id": projectId,
453  "service_id": nodeId,
454  "name": name,
455  "description": description,
456  "parameters": parameters
457  }
458  )
459 
460  if response.hasFailed():
461  raise NetworkRequestError(response, "Failed to create experiment")
462 
463  return cls.decode(response.json[0])

◆ submitMetrics()

bool coretex.coretex.experiment.experiment.Experiment.submitMetrics (   self,
Dict[str, Tuple[float, float]]  metricValues 
)
    Appends metric values for the provided metrics

    Parameters
    ----------
    metricValues : Dict[str, Tuple[float, float]]
Values of metrics in this format {"name": x, y}

    Example
    -------
    >>> from coretex import ExecutingExperiment
    \b
    >>> result = ExecutingExperiment.current().submitMetrics({
    "loss": (epoch, logs["loss"]),
    "accuracy": (epoch, logs["accuracy"]),
})
    >>> print(result)
    True

Definition at line 256 of file experiment.py.

256  def submitMetrics(self, metricValues: Dict[str, Tuple[float, float]]) -> bool:
257  """
258  Appends metric values for the provided metrics
259 
260  Parameters
261  ----------
262  metricValues : Dict[str, Tuple[float, float]]
263  Values of metrics in this format {"name": x, y}
264 
265  Example
266  -------
267  >>> from coretex import ExecutingExperiment
268  \b
269  >>> result = ExecutingExperiment.current().submitMetrics({
270  "loss": (epoch, logs["loss"]),
271  "accuracy": (epoch, logs["accuracy"]),
272  })
273  >>> print(result)
274  True
275  """
276 
277  metrics = [{
278  "timestamp": time.time(),
279  "metric": k,
280  "x": v[0],
281  "y": v[1]} for k, v in metricValues.items()]
282 
283  parameters: Dict[str, Any] = {
284  "experiment_id": self.id,
285  "metrics": metrics
286  }
287 
288  endpoint = "model-queue/metrics"
289  response = networkManager.genericJSONRequest(
290  endpoint = endpoint,
291  requestType = RequestType.post,
292  parameters = parameters
293  )
294 
295  return not response.hasFailed()
296 

◆ updateStatus()

bool coretex.coretex.experiment.experiment.Experiment.updateStatus (   self,
ExperimentStatus  status,
Optional[str]   message = None,
bool   notifyServer = True 
)
    Updates Experiment status, if message parameter is None
    default message value will be used\n
    Some Experiment statuses do not have default message

    Parameters
    ----------
    status : ExperimentStatus
ExperimentStatus type
    message : Optional[str]
Descriptive message for experiment status
    notifyServer : bool
if True update request will be sent to Coretex.ai

    Example
    -------
    >>> from coretex import ExecutingExperiment, ExperimentStatus
    \b
    >>> ExecutingExperiment.current().updateStatus(
    ExperimentStatus.completedWithSuccess
)
    True

Definition at line 155 of file experiment.py.

155  def updateStatus(self, status: ExperimentStatus, message: Optional[str] = None, notifyServer: bool = True) -> bool:
156  """
157  Updates Experiment status, if message parameter is None
158  default message value will be used\n
159  Some Experiment statuses do not have default message
160 
161  Parameters
162  ----------
163  status : ExperimentStatus
164  ExperimentStatus type
165  message : Optional[str]
166  Descriptive message for experiment status
167  notifyServer : bool
168  if True update request will be sent to Coretex.ai
169 
170  Example
171  -------
172  >>> from coretex import ExecutingExperiment, ExperimentStatus
173  \b
174  >>> ExecutingExperiment.current().updateStatus(
175  ExperimentStatus.completedWithSuccess
176  )
177  True
178  """
179 
180  with Experiment.__statusUpdateLock:
181  if message is None:
182  message = status.defaultMessage
183 
184  assert(len(message) > 10) # Some information needs to be sent to Coretex.ai
185  self.status = status
186  self.__lastStatusMessage = message
187 
188  parameters: Dict[str, Any] = {
189  "id": self.id,
190  "status": status.value,
191  "status_message": message
192  }
193 
194  if notifyServer:
195  # TODO: Should API rename this too?
196  endpoint = "model-queue/job-status-update"
197  response = networkManager.genericJSONRequest(
198  endpoint = endpoint,
199  requestType = RequestType.post,
200  parameters = parameters
201  )
202 
203  if response.hasFailed():
204  logging.getLogger("coretexpylib").error(">> [Coretex] Error while updating experiment status")
205 
206  return not response.hasFailed()
207 
208  return True
209 

The documentation for this class was generated from the following file: