# CMAP

LINCS L1000 / Connectivity Map drug-reversal search. Given a set of up- and down-regulated genes (or a differential-expression table), ranks drugs whose perturbation signatures mimic (Tau > 0) or reverse (Tau < 0) the query signature. Returns ranked Tau / NCS scores with drug name, target, and MoA.

## 基础信息

| 项目 | 值 |
|------|-----|
| Base URL | `https://sciminer.tech/console/api` |
| API Endpoint | `/v1/internal/tools/invoke` |
| Content-Type | `application/json` |
| Authentication | `X-Auth-Token: <YOUR_API_KEY>` |

## 1. TYPE 2 (code 20001): accepts a CMap query, returns a task_id immediately,
and posts the ranked drug table + chart to the platform when computation finishes.

**Tool Name:** `predict_async_predict_async_post`

**Method:** `POST`

### 参数

| 参数名 | 类型 | 必需 | 说明 | 枚举值 |
|--------|------|------|------|--------|
| `direction` | `select` | ✗ | Post-score filter on Tau sign; does not change scores. 'both' = keep all; 'mimic' = Tau>0 (drug mimics query); 'reverse' = Tau<0 (drug reverses query, i.e. therapeutic candidates). | `both`, `mimic`, `reverse` |
| `up_genes` | `string` | ✗ | Up-regulated genes of the query signature; engine finds drugs that mimic (Tau>0) or reverse (Tau<0) it. Symbols or Entrez IDs, separated by newline/comma/semicolon/space. Ignored if de_file is given; at least 10 mapped genes required. |  |
| `down_genes` | `string` | ✗ | Down-regulated genes of the query signature, same format as up_genes. Up/down direction drives the mimic/reverse call, so assign them correctly. |  |
| `de_file` | `file` | ✗ | DE table (csv/tsv/txt/xlsx) as an alternative to pasting gene lists: top/bottom genes by logFC auto-form the query signature. Columns must be exactly 'Gene' and 'logFC'. Overrides up_genes/down_genes.<br/>file suffix: `csv`, `tsv`, `txt`, `xlsx`, `xls` |  |
| `top_n` | `number` | ✗ | DE-file mode only: take top N up + top N down genes by logFC as the signature (size = 2*N). Range 10-2000. |  |
| `top_k` | `number` | ✗ | Cap on ranked drug hits returned (1-1000). Applied before direction filtering, so mimic/reverse may yield fewer rows. |  |
| `cell_lines` | `string` | ✗ | Restrict the search to perturbations in these cell lines (applied before scoring, so it reshapes Tau normalization). 'All' = no filter; else comma/semicolon list, e.g. 'A375,MCF7'. Any 'all' in the list disables filtering. |  |
| `wtcs` | `string` | ✗ | WTCS band 'lower,upper' in [-1,1]; perturbations whose connection score falls inside [lower,upper] are dropped as too weak before Tau ranking. Tighten (e.g. '-0.1,0.1') for stricter, loosen for more permissive. |  |
| `tau` | `string` | ✗ | Tau cutoffs 'pos_min,neg_max' in [-100,100]; keep only Tau>=pos_min (mimic) or Tau<=neg_max (reverse), reporting only the strongest hits. pos_min in [0,100], neg_max in [-100,0]. |  |

### 示例代码

#### Python

```python
import requests

BASE_URL = "https://sciminer.tech/console/api"
API_KEY = "<YOUR_API_KEY>"
endpoint = "/v1/internal/tools/invoke"

# If the invoked API includes FILE-type parameters, upload the file first to obtain a `file_id`,
# then fill the corresponding field in `parameters` with the returned `file_id`.
# File upload example (form-data, parameter name is `file`):

# files = {'file': open('path/to/your_file.ext', 'rb')}
# upload_url = f"{BASE_URL}/v1/internal/tools/file"
# resp_upload = requests.post(upload_url, files=files, headers={"X-Auth-Token": f"{API_KEY}"}, timeout=60)
# resp_upload.raise_for_status()
# file_id = resp_upload.json().get("file_id")
# print(f"File uploaded successfully, file_id: {file_id}")
# # Then set the `file_id` in the corresponding field of `payload['parameters']`, for example: payload['parameters']["your_file_param_name"] = file_id

headers = {
    "X-Auth-Token": f"{API_KEY}",
    "Content-Type": "application/json",
}

payload = {
    "provider_name": "CMAP",
    "tool_name": "predict_async_predict_async_post",
    "parameters": {
    "direction": "<DIRECTION>",
    "up_genes": "",
    "down_genes": "",
    "de_file": "<DE_FILE_FILE_ID>",
    "top_n": 50,
    "top_k": 50,
    "cell_lines": "All",
    "wtcs": "-0.2,0.2",
    "tau": "90,-90"
},
    # The job name is an optional parameter.
    #"job_name": "xxx",
}

# Step 1: Submit the task.
# Call the /invoke endpoint to start the task and obtain a task_id.
print("1. Submitting task...")
resp_submit = requests.post(f"{BASE_URL}{endpoint}", json=payload, headers=headers, timeout=30)
resp_submit.raise_for_status()
task_id = resp_submit.json().get("task_id")
print(f"Task ID: {task_id}")

# Step 2: Poll for the result.
# Use the task_id obtained above to call the /result endpoint to check status and fetch the result.
# If this tool takes a long time, you can increase the max_retries parameter or after exceeding the maximum number of times, you can use the task_id to re-request.
status_url = f"https://sciminer.tech/console/api/v1/internal/tools/result"
max_retries = 300
status = "PENDING"
for i in range(max_retries):
    print(f"Polling status (attempt {i+1}/{max_retries})...")
    resp_status = requests.get(
        status_url,
        params={"task_id": task_id},
        headers=headers,
        timeout=10
    )
    resp_status.raise_for_status()
    
    result = resp_status.json()
    status = result.get("status")
    print(f"Status: {status}")
    
    if status == "SUCCESS":
        print("✅ Task completed successfully！")
        print(f"Result: {result.get('result')}")
        break
    elif status == "FAILURE":
        print(f"❌ Task failed: {result.get('result')}")
        break
    else:
        # Wait 2 seconds before retrying
        import time
        time.sleep(2)
else:
    print("⏱️  Maximum retry attempts reached. The task is still running.")
```


---

## User Interface URL

> When the user needs a tool recommendation, output the URL.

**URL:** <https://sciminer.tech/utility/tool/CMAP>
