Metadata-Version: 2.4
Name: aesim.simba
Version: 2026.10.21a1
Summary: Power Electronics and Motor Drive Simulation
Home-page: https://simba.io
Author: AESIM.tech
Author-email: contact@aesim.tech
License: By using aesim.simba, you agree to the license agreement available here: https://www.simba.io/static/EULA.pdf
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: pythonnet>=3.1.0rc0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# SIMBA Python API

The Simba Python Module (aesim.simba) is a Python package that contains hundreds of functions providing direct access to SIMBA such as creating a circuit, modifying parameters, running a simulation, and retrieving results. aesim.simba is independent and does not require to have SIMBA installed to be used.

## Installation

The easiest way to install the Python API is using pip:

`pip install aesim.simba`

## Requirements

The current version of _aesim.simba_ is compatible with Windows, macOS and Linux (64-bit). 

## Activation
The deployment key available on your [account profile page](https://www.simba.io/profile_account/) must be used to activate _aesim.simba_. Two methods are available:

### Using Environment Variable

The easiest way to activate pysimba is to set the environment variable `SIMBA_DEPLOYMENT_KEY` value to your deployment key. To add a new environment variable in Windows: 

* Open the Start Search, type in “env”, and choose “Edit the system environment variables”:
* Click the “Environment Variables…” button.
* Set the environment variables as needed. The New button adds an additional variable.

### Code-based Activation

The _License_ API can be also used to activate _aesim.simba_.

``` python
from aesim.simba import License
License.Activate('*** YOUR DEPLOYMENT KEY ***')
```

### Background License Validation
Desktop and Python use the same background validation policy: multi-user licenses
are checked every five minutes, and individual online licenses once every 24 hours
while the process runs. Online activations nearing their expiration can be renewed
earlier. Failed checks can be retried after five minutes without extending the
signed license's validity. Routine checks and network failures are silent; explicit
account revocations remove the rights as usual. Individual offline licenses are
checked locally only, and `SIMBA_OFFLINE_MODE` disables all server checks.
Python starts checking after a license has been loaded, using one timer per process.
The timer is stopped at interpreter exit without waiting for a network request.

### Compute License (cloud and cluster workers)
A Compute license runs _aesim.simba_ on servers, cloud instances or containers without
binding it to a machine. When Powersys has enabled the Compute license of your account, the
license administrator creates keys on the
[Compute licenses page](https://www.simba.io/profile/compute/) of the simba.io profile and
stores each secret in a secret manager (it is shown only once). Each worker process then
obtains a short lease from the license server, renews it in the background and releases it
at exit; a permanent connection to the license server is required.

Compute lease requests take precedence over `SIMBA_OFFLINE_MODE`: acquiring,
renewing and releasing Compute leases still require network access when that
variable is enabled.

Compute mode is selected for the process lifetime when either Compute credential
variable is present; both nonempty credentials are required. A failed acquisition,
expired lease or call to `License.StopCompute()` never falls back to a stored regular
license. To use a regular license, stop the worker, unset `SIMBA_COMPUTE_KEY_ID` and
`SIMBA_COMPUTE_SECRET`, then start a new process with the usual licensing configuration.
Changing these variables in a running process does not change its license mode.

Network failures, HTTP 408 timeouts, exhausted slots, rate limits and temporary
server errors are retried with exponential delays from 15 seconds up to five minutes. Renewals
are scheduled no later than half the native remaining lifetime, measured
in milliseconds. Retries after errors also take the remaining lifetime into account,
with a minimum one-second interval; in the final second or after expiry they use
normal backoff to avoid busy-polling. Two leases issued in the same second can collide with replay
protection: a rejected acquisition is released and retried after two seconds;
an existing lease keeps its original expiry. The signed
lease's expiry is never extended locally. A response received after its signed expiry
is rejected natively but retried automatically with normal backoff. A rejected
acquisition is released before retrying; a rejected renewal retains the rotated
renewal token and does not release any previous valid allocation. HTTP 401/403 credential refusals suspend
automatic attempts: correct the credentials and call `License.ActivateCompute`
again, or restart the worker. Stopping Compute cancels renewals and prevents new
calculations immediately; calculations already authorized can finish.

On Linux, lease expiration uses `CLOCK_BOOTTIME`, which includes host suspend time.
Resuming a suspended host does not restore the lifetime of a lease that has expired.

Compute rights belong to one process. After a POSIX `fork()`, the child discards
the inherited rights and uses a new nonce. It must explicitly acquire its own
lease and never renew or release the parent's allocation. Prefer starting a fresh
worker process and initializing SIMBA there: this protection does not make an
already initialized .NET runtime safe to reuse after `fork()`.

Diagnostic messages are written in English to standard error. They identify the
failure, the retry delay (or suspended retries), and whether the current lease still
allows new calculations. Repeated messages for the same condition are limited to
one per minute; recovery is reported immediately. Credentials and raw server error
bodies are never included.

### Licensing Environment Variables
| Variable | Default | Meaning |
|---|---|---|
| `SIMBA_DEPLOYMENT_KEY` | not set | Deployment key of a regular license (see above) |
| `SIMBA_COMPUTE_KEY_ID` | not set | Compute license key ID; with `SIMBA_COMPUTE_SECRET`, selects the Compute license |
| `SIMBA_COMPUTE_SECRET` | not set | Secret of the Compute license key (keep it in a secret manager) |
| `SIMBA_COMPUTE_SLOTS` | `1` | Simultaneous simulations of one Python process with a Compute license |

### License Usage Data
With an online license, _aesim.simba_ reports the use of the license to the SIMBA license
server, like SIMBA Desktop: one session per Python process and, every 12 hours,
a report with totals per simulation type (transient, AC sweep, FMI):
number of simulations, results (completed, error, aborted), refusals and their reason,
cumulated and longest durations, highest number of simultaneous simulations, and the
JMAG / detailed switch model tokens used. Individual simulations are not reported.
The session also describes the environment: operating system, processor count, whether it
runs in a container or a continuous integration service, and the host and user names as
SHA-256 hashes (never in clear). Circuits, parameters and results are never sent.
At process exit the final report is saved in the existing local queue for the next
start, without an additional network wait. Network failures remain eligible for
retry; invalid reports rejected with HTTP 400 are discarded silently.
The shared telemetry queue keeps at most five reports and 1 MiB on disk, removing
the oldest reports first. A report exceeding 1 MiB on its own is discarded silently.

| Environment variable | Default | Meaning |
|---|---|---|
| `SIMBA_LICENSE_USAGE_REPORT_INTERVAL_HOURS` | `12` | Hours between two usage reports; the final report is queued at exit |
| `SIMBA_LICENSE_USAGE_DRAIN_SECONDS` | `60` | Seconds between two local reads of the solver usage journal (no network) |
| `SIMBA_OFFLINE_MODE` | not set | Disables all telemetry, including usage reports |

Missing, invalid or out-of-range interval settings use the defaults above without
console messages or startup errors. After lost journal events, the running count
is resynchronized from the native drain snapshot. The incomplete period retains
its lost-event count and reports a peak of zero, rather than an unreliable peak.

Deferred review items: concurrent event ordering can still overstate peaks in
periods without loss. Server-side recovery of identity alerts for future reports,
durable alert scheduling, and historical quota attribution for delayed reports
are tracked separately and are not changed here.

## API Documentation
The API documentation is available [here](https://www.simba.io/doc/python_api/api_index/). 

The installed package also provides API docstrings and type annotations. In an interactive
Python session, use `help(aesim.simba.DFTCalculatorJob)` or your editor's hover help to
discover constructor overloads, properties, and supported analysis jobs.

## Performance
Running a simulation using the Python API is significantly faster than using the SIMBA User Interface because there is no overhead.

## Quick Example
The following example opens the Flyback Converter Example available in SIMBA, runs it, and plots the output voltage.

``` python
#%% Load modules
from aesim.simba import DesignExamples
import matplotlib.pyplot as plt

#%% Load project
flybackConverter = DesignExamples.DCDC_Flyback()

#%% Get the job object and solve the system
job = flybackConverter.TransientAnalysis.NewJob()
status = job.Run()

#%% Get results
t = job.TimePoints
Vout = job.GetSignalByName('R2 - Instantaneous Voltage').DataPoints

#%% Plot Curve
fig, ax = plt.subplots()
ax.set_title(flybackConverter.Name)
ax.set_ylabel('Vout (V)')
ax.set_xlabel('time (s)')
ax.plot(t,Vout)

# %%
```

## DFT Example

The following example computes the magnitude spectrum of the flyback output over the final
ten switching periods. `DFTSettings(frequency, periods, harmonics)` includes the DC component
and the requested harmonics in the resulting signal.

``` python
from aesim.simba import DFTCalculatorJob, DFTSettings, DesignExamples, Status
import matplotlib.pyplot as plt

design = DesignExamples.DCDC_Flyback()
transient_job = design.TransientAnalysis.NewJob()
if transient_job.Run() != Status.OK:
    raise RuntimeError("Transient simulation failed")

vout = transient_job.GetSignalByName("R2 - Instantaneous Voltage")
dft_job = DFTCalculatorJob(DFTSettings(100e3, 10, 20), [vout])
if dft_job.Run() != Status.OK:
    raise RuntimeError("DFT calculation failed")

spectrum = dft_job.Signals[0]
fig, ax = plt.subplots()
ax.stem(spectrum.TimePoints, spectrum.DataPoints)
ax.set(xlabel="Frequency (Hz)", ylabel=f"Amplitude ({vout.Unit})")
ax.grid()
plt.show()
```

## More Examples
A collection of simple Python script examples using the SIMBA Python API is available on this [GitHub repository](https://github.com/aesim-tech/simba-python-examples)


Copyright (c) 2019-2020 AESIM.tech
