Compare commits
8 Commits
develop-ba
...
dd0f7eaf05
| Author | SHA1 | Date | |
|---|---|---|---|
| dd0f7eaf05 | |||
| 7d828e2be0 | |||
| 8ae4f36174 | |||
| 451986082a | |||
| ca5a9a12be | |||
| 21181c80ec | |||
| 5aa39637dc | |||
| 22179f0d90 |
@ -7,10 +7,10 @@ repos:
|
|||||||
- id: trailing-whitespace
|
- id: trailing-whitespace
|
||||||
exclude: epiuclid/schemas/
|
exclude: epiuclid/schemas/
|
||||||
- id: end-of-file-fixer
|
- id: end-of-file-fixer
|
||||||
exclude: ^epiuclid/schemas/|^static/js/ketcher3/
|
exclude: epiuclid/schemas/
|
||||||
- id: check-yaml
|
- id: check-yaml
|
||||||
- id: check-added-large-files
|
- id: check-added-large-files
|
||||||
exclude: ^static/images/|^epiuclid/schemas/|^fixtures/|^static/js/ketcher3/
|
exclude: ^static/images/|^epiuclid/schemas/|^fixtures/
|
||||||
|
|
||||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
rev: v0.13.3
|
rev: v0.13.3
|
||||||
|
|||||||
19
Dockerfile
@ -6,23 +6,18 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
|
|||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
build-essential \
|
build-essential \
|
||||||
libpq-dev \
|
libpq-dev \
|
||||||
curl \
|
curl \
|
||||||
openssh-client \
|
openssh-client \
|
||||||
git \
|
git \
|
||||||
ca-certificates \
|
nodejs \
|
||||||
|
npm \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# Install Node 22 + pnpm
|
# Install pnpm
|
||||||
RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
|
RUN npm install -g pnpm
|
||||||
&& apt-get update \
|
|
||||||
&& apt-get install -y --no-install-recommends nodejs \
|
|
||||||
&& corepack enable \
|
|
||||||
&& corepack prepare pnpm@latest --activate \
|
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
|
||||||
|
|
||||||
RUN curl -LsSf https://astral.sh/uv/install.sh | sh
|
RUN curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||||
ENV PATH="/root/.local/bin:${PATH}"
|
ENV PATH="/root/.local/bin:${PATH}"
|
||||||
@ -35,21 +30,19 @@ RUN mkdir -p -m 0700 /root/.ssh \
|
|||||||
&& ssh-keyscan git.envipath.com >> /root/.ssh/known_hosts
|
&& ssh-keyscan git.envipath.com >> /root/.ssh/known_hosts
|
||||||
|
|
||||||
# We'll need access to private repos, let docker make use of host ssh agent and use it like:
|
# We'll need access to private repos, let docker make use of host ssh agent and use it like:
|
||||||
# docker build --ssh default -t envipath/envipy-bayer:1.0 .
|
# docker build --ssh default -t envipath/envipy:1.0 .
|
||||||
RUN --mount=type=ssh \
|
RUN --mount=type=ssh \
|
||||||
uv sync --locked --extra ms-login --extra pepper-plugin
|
uv sync --locked --extra ms-login --extra pepper-plugin
|
||||||
|
|
||||||
# Now copy source and do a final sync to install the project itself
|
# Now copy source and do a final sync to install the project itself
|
||||||
# Ensure .dockerignore is reasonable
|
# Ensure .dockerignore is reasonable
|
||||||
COPY bb4g bb4g
|
|
||||||
COPY biotransformer biotransformer
|
|
||||||
COPY bayer bayer
|
COPY bayer bayer
|
||||||
COPY bridge bridge
|
COPY bridge bridge
|
||||||
|
COPY biotransformer biotransformer
|
||||||
COPY envipath envipath
|
COPY envipath envipath
|
||||||
COPY epapi epapi
|
COPY epapi epapi
|
||||||
COPY epauth epauth
|
COPY epauth epauth
|
||||||
COPY epdb epdb
|
COPY epdb epdb
|
||||||
COPY epiuclid epiuclid
|
|
||||||
COPY fixtures fixtures
|
COPY fixtures fixtures
|
||||||
COPY migration migration
|
COPY migration migration
|
||||||
COPY pepper pepper
|
COPY pepper pepper
|
||||||
|
|||||||
@ -1,178 +0,0 @@
|
|||||||
import enum
|
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
from envipy_additional_information import GroupEnum as G
|
|
||||||
from envipy_additional_information import SubcategoryEnum as S
|
|
||||||
from envipy_additional_information import (
|
|
||||||
register,
|
|
||||||
register_parser_command,
|
|
||||||
EnviPyModel,
|
|
||||||
# EnviPyModelParser,
|
|
||||||
Interval,
|
|
||||||
UIConfig,
|
|
||||||
IntervalConfig,
|
|
||||||
WidgetType,
|
|
||||||
registry,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@register(keyname="compoundlabel", groups=[S.MISC, G.SLUDGE, G.SEDIMENT, G.SOIL])
|
|
||||||
class CompoundLabel(EnviPyModel):
|
|
||||||
label: str
|
|
||||||
|
|
||||||
class UI:
|
|
||||||
title = "Compound Label"
|
|
||||||
label = UIConfig(widget=WidgetType.TEXT, label="Label", order=1)
|
|
||||||
|
|
||||||
|
|
||||||
# TODO Expose EnviPyModelParser in lib and subclass
|
|
||||||
@register_parser_command("compoundlabel")
|
|
||||||
class CompoundLabelParser:
|
|
||||||
@staticmethod
|
|
||||||
def from_string(data: str) -> CompoundLabel:
|
|
||||||
return CompoundLabel(label=data)
|
|
||||||
|
|
||||||
|
|
||||||
@register(keyname="studywaterstoragecapacity", groups=[S.MISC, G.SLUDGE, G.SEDIMENT, G.SOIL])
|
|
||||||
class StudyWaterStorageCapacity(EnviPyModel):
|
|
||||||
capacity: str
|
|
||||||
|
|
||||||
class UI:
|
|
||||||
title = "Study Water Storage Capacity"
|
|
||||||
capacity = UIConfig(widget=WidgetType.TEXT, label="Study Water Storage Capacity", order=1)
|
|
||||||
|
|
||||||
|
|
||||||
# TODO Expose EnviPyModelParser in lib and subclass
|
|
||||||
@register_parser_command("studywst")
|
|
||||||
class StudyWaterStorageCapacityParser:
|
|
||||||
@staticmethod
|
|
||||||
def from_string(data: str) -> StudyWaterStorageCapacity:
|
|
||||||
return StudyWaterStorageCapacity(capacity=data)
|
|
||||||
|
|
||||||
|
|
||||||
class ObservationType(enum.Enum):
|
|
||||||
OBSERVED = "observed"
|
|
||||||
APPLIED = "applied"
|
|
||||||
NA = 'NA'
|
|
||||||
|
|
||||||
|
|
||||||
@register(keyname="observation", groups=[S.MISC, G.SLUDGE, G.SEDIMENT, G.SOIL])
|
|
||||||
class Observation(EnviPyModel):
|
|
||||||
type: ObservationType
|
|
||||||
min_value: Optional[float] = None
|
|
||||||
max_value: Optional[float] = None
|
|
||||||
|
|
||||||
class UI:
|
|
||||||
title = "Observation"
|
|
||||||
type = UIConfig(widget=WidgetType.SELECT, label="Observed or Applied", order=1)
|
|
||||||
min_value = UIConfig(widget=WidgetType.NUMBER, label="Min Value", order=2)
|
|
||||||
max_value = UIConfig(widget=WidgetType.NUMBER, label="Max Value", order=3)
|
|
||||||
|
|
||||||
|
|
||||||
# TODO Expose EnviPyModelParser in lib and subclass
|
|
||||||
@register_parser_command("observation")
|
|
||||||
class ObservationParser:
|
|
||||||
@staticmethod
|
|
||||||
def from_string(data: str) -> Observation:
|
|
||||||
parts = data.split(";")
|
|
||||||
|
|
||||||
observation_type = ObservationType(parts[0])
|
|
||||||
min_value = None
|
|
||||||
if parts[1]:
|
|
||||||
try:
|
|
||||||
min_value = float(parts[1])
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
max_value = None
|
|
||||||
if parts[2]:
|
|
||||||
try:
|
|
||||||
max_value = float(parts[2])
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return Observation(type=observation_type, min_value=min_value, max_value=max_value)
|
|
||||||
|
|
||||||
|
|
||||||
@register(keyname="kinetics", groups=[S.MISC, G.SLUDGE, G.SEDIMENT, G.SOIL])
|
|
||||||
class Kinetics(EnviPyModel):
|
|
||||||
dt50: Interval[float]
|
|
||||||
normalized_dt50: bool
|
|
||||||
chi2err: Optional[float] = None
|
|
||||||
t_test: Optional[float] = None
|
|
||||||
swarc: Optional[float] = None
|
|
||||||
visual_fit: Optional[int] = None
|
|
||||||
comment: str
|
|
||||||
source: str
|
|
||||||
kinetic_model: str
|
|
||||||
k1: Optional[float] = None
|
|
||||||
k2: Optional[float] = None
|
|
||||||
g: Optional[float] = None
|
|
||||||
tb: Optional[float] = None
|
|
||||||
alpha: Optional[float] = None
|
|
||||||
beta: Optional[float] = None
|
|
||||||
|
|
||||||
class UI:
|
|
||||||
title = "Kinetics"
|
|
||||||
|
|
||||||
# Field config
|
|
||||||
dt50 = IntervalConfig(label="DT50 Range", order=1, unit="d")
|
|
||||||
normalized_dt50 = UIConfig(widget=WidgetType.CHECKBOX, label="Normalized DT50", order=2)
|
|
||||||
chi2err = UIConfig(widget=WidgetType.NUMBER, label="Chi2err", order=3)
|
|
||||||
t_test = UIConfig(widget=WidgetType.NUMBER, label="T-Test", order=4)
|
|
||||||
swarc = UIConfig(widget=WidgetType.NUMBER, label="SWARC", order=5)
|
|
||||||
visual_fit = UIConfig(widget=WidgetType.NUMBER, label="Visual Fit", order=6)
|
|
||||||
comment = UIConfig(widget=WidgetType.TEXTAREA, label="Comments", order=7)
|
|
||||||
source = UIConfig(widget=WidgetType.TEXT, label="Source", order=8)
|
|
||||||
kinetic_model = UIConfig(widget=WidgetType.SELECT, label="Kinetic Model", order=9)
|
|
||||||
k1 = UIConfig(widget=WidgetType.NUMBER, label="K1", order=10)
|
|
||||||
k2 = UIConfig(widget=WidgetType.NUMBER, label="K2", order=11)
|
|
||||||
g = UIConfig(widget=WidgetType.NUMBER, label="G", order=12)
|
|
||||||
tb = UIConfig(widget=WidgetType.NUMBER, label="TB", order=13)
|
|
||||||
alpha = UIConfig(widget=WidgetType.NUMBER, label="Alpha", order=14)
|
|
||||||
beta = UIConfig(widget=WidgetType.NUMBER, label="Beta", order=15)
|
|
||||||
|
|
||||||
|
|
||||||
# TODO Expose EnviPyModelParser in lib and subclass
|
|
||||||
@register_parser_command("kineticevaluation")
|
|
||||||
class KinecticsParser:
|
|
||||||
@staticmethod
|
|
||||||
def from_string(data: str) -> Kinetics:
|
|
||||||
parts = data.split(";")
|
|
||||||
dt50 = registry.get_parser("interval").from_string(parts[0])
|
|
||||||
normalized_dt50 = parts[1] == "true"
|
|
||||||
chi2err = float(parts[2]) if parts[2] else None
|
|
||||||
t_test = float(parts[3]) if parts[3] else None
|
|
||||||
swarc = float(parts[4]) if parts[4] else None
|
|
||||||
visual_fit = int(parts[5]) if parts[5] else None
|
|
||||||
comment = parts[6]
|
|
||||||
source = parts[7]
|
|
||||||
kinetic_model = parts[8]
|
|
||||||
k1 = float(parts[9]) if parts[9] else None
|
|
||||||
k2 = float(parts[10]) if parts[10] else None
|
|
||||||
g = float(parts[11]) if parts[11] else None
|
|
||||||
tb = float(parts[12]) if parts[12] else None
|
|
||||||
alpha = float(parts[13]) if parts[13] else None
|
|
||||||
beta = float(parts[14]) if parts[14] else None
|
|
||||||
|
|
||||||
return Kinetics(
|
|
||||||
dt50=dt50,
|
|
||||||
normalized_dt50=normalized_dt50,
|
|
||||||
chi2err=chi2err,
|
|
||||||
t_test=t_test,
|
|
||||||
swarc=swarc,
|
|
||||||
visual_fit=visual_fit,
|
|
||||||
comment=comment,
|
|
||||||
source=source,
|
|
||||||
kinetic_model=kinetic_model,
|
|
||||||
k1=k1,
|
|
||||||
k2=k2,
|
|
||||||
g=g,
|
|
||||||
tb=tb,
|
|
||||||
alpha=alpha,
|
|
||||||
beta=beta,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
print(KinecticsParser.from_string("187.0 - 187.0;false;;;;;;;AFO;;;;;;"))
|
|
||||||
@ -1,19 +1,3 @@
|
|||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
|
||||||
# Register your models here.
|
# Register your models here.
|
||||||
from .models import (
|
|
||||||
PESCompound,
|
|
||||||
PESStructure
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class PESCompoundAdmin(admin.ModelAdmin):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class PESStructureAdmin(admin.ModelAdmin):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
admin.site.register(PESCompound, PESCompoundAdmin)
|
|
||||||
admin.site.register(PESStructure, PESStructureAdmin)
|
|
||||||
|
|||||||
@ -1,40 +0,0 @@
|
|||||||
import logging
|
|
||||||
|
|
||||||
from bayer import additional_information # noqa: F401
|
|
||||||
from epdb.template_registry import register_template
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# PES Create
|
|
||||||
register_template(
|
|
||||||
"epdb.actions.collections.compound",
|
|
||||||
"actions/collections/new_pes.html",
|
|
||||||
)
|
|
||||||
register_template(
|
|
||||||
"modals.collections.compound",
|
|
||||||
"modals/collections/new_pes_modal.html",
|
|
||||||
)
|
|
||||||
register_template(
|
|
||||||
"epdb.actions.objects.pathway.add",
|
|
||||||
"actions/objects/pathway_add_pes.html",
|
|
||||||
)
|
|
||||||
register_template(
|
|
||||||
"epdb.modals.objects.pathway.add",
|
|
||||||
"modals/objects/add_pathway_pes_node_modal.html"
|
|
||||||
)
|
|
||||||
|
|
||||||
# PES Viz
|
|
||||||
register_template(
|
|
||||||
"epdb.objects.compound.viz",
|
|
||||||
"objects/compound_viz.html",
|
|
||||||
)
|
|
||||||
|
|
||||||
register_template(
|
|
||||||
"epdb.objects.compound_structure.viz",
|
|
||||||
"objects/compound_structure_viz.html",
|
|
||||||
)
|
|
||||||
|
|
||||||
register_template(
|
|
||||||
"epdb.objects.node.viz",
|
|
||||||
"objects/node_viz.html",
|
|
||||||
)
|
|
||||||
20
bayer/migrations/0003_package_data_pool.py
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
# Generated by Django 6.0.3 on 2026-04-14 19:07
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('bayer', '0002_initial'),
|
||||||
|
('epdb', '0023_alter_compoundstructure_options_and_more'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='package',
|
||||||
|
name='data_pool',
|
||||||
|
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='epdb.group', verbose_name='Data pool'),
|
||||||
|
),
|
||||||
|
]
|
||||||
@ -1,41 +0,0 @@
|
|||||||
# Generated by Django 6.0.3 on 2026-04-17 21:22
|
|
||||||
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('bayer', '0002_initial'),
|
|
||||||
('epdb', '0023_alter_compoundstructure_options_and_more'),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='PESCompound',
|
|
||||||
fields=[
|
|
||||||
('compound_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='epdb.compound')),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'abstract': False,
|
|
||||||
},
|
|
||||||
bases=('epdb.compound',),
|
|
||||||
),
|
|
||||||
migrations.CreateModel(
|
|
||||||
name='PESStructure',
|
|
||||||
fields=[
|
|
||||||
('compoundstructure_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='epdb.compoundstructure')),
|
|
||||||
('pes_link', models.URLField(verbose_name='PES Link')),
|
|
||||||
],
|
|
||||||
options={
|
|
||||||
'abstract': False,
|
|
||||||
},
|
|
||||||
bases=('epdb.compoundstructure',),
|
|
||||||
),
|
|
||||||
migrations.AddField(
|
|
||||||
model_name='package',
|
|
||||||
name='data_pool',
|
|
||||||
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='epdb.group', verbose_name='Data pool'),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
143
bayer/models.py
@ -1,21 +1,16 @@
|
|||||||
from typing import List
|
from typing import List
|
||||||
import urllib.parse
|
|
||||||
import nh3
|
|
||||||
from django.conf import settings as s
|
from django.conf import settings as s
|
||||||
from django.db import models, transaction
|
from django.db import models
|
||||||
from django.db.models import QuerySet
|
from django.db.models import QuerySet
|
||||||
from django.urls import reverse
|
|
||||||
|
|
||||||
from epdb.models import (
|
from epdb.models import (
|
||||||
EnviPathModel,
|
EnviPathModel,
|
||||||
Compound,
|
|
||||||
CompoundStructure,
|
|
||||||
ParallelRule,
|
ParallelRule,
|
||||||
SequentialRule,
|
SequentialRule,
|
||||||
SimpleAmbitRule,
|
SimpleAmbitRule,
|
||||||
SimpleRDKitRule,
|
SimpleRDKitRule,
|
||||||
)
|
)
|
||||||
from utilities.chem import FormatConverter
|
|
||||||
|
|
||||||
|
|
||||||
class Package(EnviPathModel):
|
class Package(EnviPathModel):
|
||||||
@ -101,137 +96,3 @@ class Package(EnviPathModel):
|
|||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
db_table = "epdb_package"
|
db_table = "epdb_package"
|
||||||
|
|
||||||
|
|
||||||
class PESCompound(Compound):
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
@transaction.atomic
|
|
||||||
def create(
|
|
||||||
package: "Package", pes_data: dict, name: str = None, description: str = None, *args, **kwargs
|
|
||||||
) -> "Compound":
|
|
||||||
|
|
||||||
pes_url = pes_data["pes_url"]
|
|
||||||
|
|
||||||
# Check if we find a direct match for a given pes_link
|
|
||||||
if PESStructure.objects.filter(pes_link=pes_url, compound__package=package).exists():
|
|
||||||
# Due to normalization we might end up in having multiple structures
|
|
||||||
# All of them point to the same compound -> pick any
|
|
||||||
return PESStructure.objects.filter(pes_link=pes_url, compound__package=package).first().compound
|
|
||||||
|
|
||||||
# Generate Compound
|
|
||||||
c = PESCompound()
|
|
||||||
c.package = package
|
|
||||||
|
|
||||||
if name is not None:
|
|
||||||
# Clean for potential XSS
|
|
||||||
name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
|
||||||
|
|
||||||
if name is None or name == "":
|
|
||||||
name = f"Compound {Compound.objects.filter(package=package).count() + 1}"
|
|
||||||
|
|
||||||
c.name = name
|
|
||||||
|
|
||||||
# We have a default here only set the value if it carries some payload
|
|
||||||
if description is not None and description.strip() != "":
|
|
||||||
c.description = nh3.clean(description, tags=s.ALLOWED_HTML_TAGS).strip()
|
|
||||||
|
|
||||||
c.save()
|
|
||||||
|
|
||||||
molfile = pes_data.get("representativeStructures", [{}])[0].get("ctab")
|
|
||||||
|
|
||||||
if molfile is None:
|
|
||||||
raise ValueError("PES data does not contain a valid mol file!")
|
|
||||||
|
|
||||||
smiles = FormatConverter.to_smiles(FormatConverter.from_molfile(molfile))
|
|
||||||
|
|
||||||
standardized_smiles = FormatConverter.standardize(smiles, remove_stereo=True)
|
|
||||||
|
|
||||||
is_standardized = standardized_smiles == smiles
|
|
||||||
|
|
||||||
if not is_standardized:
|
|
||||||
_ = PESStructure.create(
|
|
||||||
c,
|
|
||||||
pes_url,
|
|
||||||
molfile,
|
|
||||||
standardized_smiles,
|
|
||||||
name="Normalized structure of {}".format(name),
|
|
||||||
description="{} (in its normalized form)".format(description),
|
|
||||||
normalized_structure=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
cs = PESStructure.create(
|
|
||||||
c,
|
|
||||||
pes_url,
|
|
||||||
molfile,
|
|
||||||
smiles,
|
|
||||||
name=name,
|
|
||||||
description=description,
|
|
||||||
normalized_structure=is_standardized
|
|
||||||
)
|
|
||||||
|
|
||||||
c.default_structure = cs
|
|
||||||
c.save()
|
|
||||||
|
|
||||||
return c
|
|
||||||
|
|
||||||
|
|
||||||
class PESStructure(CompoundStructure):
|
|
||||||
pes_link = models.URLField(blank=False, null=False, verbose_name="PES Link")
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
@transaction.atomic
|
|
||||||
def create(
|
|
||||||
compound: Compound,
|
|
||||||
pes_link: str,
|
|
||||||
molfile: str,
|
|
||||||
smiles: str,
|
|
||||||
name: str = None,
|
|
||||||
description: str = None,
|
|
||||||
*args,
|
|
||||||
**kwargs
|
|
||||||
):
|
|
||||||
if compound.pk is None:
|
|
||||||
raise ValueError("Unpersisted Compound! Persist compound first!")
|
|
||||||
|
|
||||||
cs = PESStructure()
|
|
||||||
# Clean for potential XSS
|
|
||||||
if name is not None:
|
|
||||||
cs.name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
|
||||||
|
|
||||||
if description is not None:
|
|
||||||
cs.description = nh3.clean(description, tags=s.ALLOWED_HTML_TAGS).strip()
|
|
||||||
|
|
||||||
cs.smiles = smiles
|
|
||||||
cs.molfile = molfile
|
|
||||||
cs.pes_link = pes_link
|
|
||||||
cs.compound = compound
|
|
||||||
|
|
||||||
if "normalized_structure" in kwargs:
|
|
||||||
cs.normalized_structure = kwargs["normalized_structure"]
|
|
||||||
|
|
||||||
cs.save()
|
|
||||||
|
|
||||||
return cs
|
|
||||||
|
|
||||||
@transaction.atomic
|
|
||||||
def add_structure(
|
|
||||||
self,
|
|
||||||
smiles: str,
|
|
||||||
name: str = None,
|
|
||||||
description: str = None,
|
|
||||||
default_structure: bool = False,
|
|
||||||
*args,
|
|
||||||
**kwargs,
|
|
||||||
) -> "CompoundStructure":
|
|
||||||
raise ValueError("Not supported!")
|
|
||||||
|
|
||||||
def d3_json(self):
|
|
||||||
return {
|
|
||||||
"is_pes": True,
|
|
||||||
"pes_link": self.pes_link,
|
|
||||||
# Will overwrite image from Node
|
|
||||||
"image": f"{reverse('depict_pes')}?pesLink={urllib.parse.quote(self.pes_link)}",
|
|
||||||
"image_type": "png",
|
|
||||||
}
|
|
||||||
|
|||||||
@ -1,9 +0,0 @@
|
|||||||
{% if meta.can_edit %}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="btn btn-primary btn-sm"
|
|
||||||
onclick="document.getElementById('new_pes_modal').showModal(); return false;"
|
|
||||||
>
|
|
||||||
New PES
|
|
||||||
</button>
|
|
||||||
{% endif %}
|
|
||||||
@ -1,8 +0,0 @@
|
|||||||
<li>
|
|
||||||
<a
|
|
||||||
class="button"
|
|
||||||
onclick="document.getElementById('add_pathway_pes_node_modal').showModal(); return false;"
|
|
||||||
>
|
|
||||||
<i class="glyphicon glyphicon-plus"></i> Add PES</a
|
|
||||||
>
|
|
||||||
</li>
|
|
||||||
@ -9,7 +9,11 @@
|
|||||||
|
|
||||||
reset() {
|
reset() {
|
||||||
this.isSubmitting = false;
|
this.isSubmitting = false;
|
||||||
this.packageClassification = null;
|
this.selectedType = '';
|
||||||
|
this.buildAppDomain = false;
|
||||||
|
this.requiresRulePackages = false;
|
||||||
|
this.requiresDataPackages = false;
|
||||||
|
this.additional_parameters = null;
|
||||||
},
|
},
|
||||||
|
|
||||||
setFormData(data) {
|
setFormData(data) {
|
||||||
@ -133,8 +137,10 @@
|
|||||||
class="select select-bordered w-full"
|
class="select select-bordered w-full"
|
||||||
>
|
>
|
||||||
<option value="" disabled selected>Select Data Pool</option>
|
<option value="" disabled selected>Select Data Pool</option>
|
||||||
{% for obj in meta.secret_groups %}
|
{% for obj in meta.available_groups %}
|
||||||
|
{% if obj.secret %}
|
||||||
<option value="{{ obj.url }}">{{ obj.name|safe }}</option>
|
<option value="{{ obj.url }}">{{ obj.name|safe }}</option>
|
||||||
|
{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,174 +0,0 @@
|
|||||||
{% load static %}
|
|
||||||
|
|
||||||
<dialog
|
|
||||||
id="new_pes_modal"
|
|
||||||
class="modal"
|
|
||||||
x-data="{
|
|
||||||
isSubmitting: false,
|
|
||||||
pesLink: null,
|
|
||||||
pesVizHtml: '',
|
|
||||||
|
|
||||||
reset() {
|
|
||||||
this.isSubmitting = false;
|
|
||||||
},
|
|
||||||
|
|
||||||
get isPESSet() {
|
|
||||||
console.log(this.pesLink);
|
|
||||||
return this.pesLink !== null;
|
|
||||||
},
|
|
||||||
|
|
||||||
updatePesViz() {
|
|
||||||
if (!this.isPESSet) {
|
|
||||||
this.pesVizHtml = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const img = new Image();
|
|
||||||
img.src = '{% url 'depict_pes' %}?pesLink=' + encodeURIComponent(this.pesLink);
|
|
||||||
img.style.width = '100%';
|
|
||||||
img.style.height = '100%';
|
|
||||||
img.style.objectFit = 'cover';
|
|
||||||
|
|
||||||
img.onload = () => {
|
|
||||||
this.pesVizHtml = img.outerHTML;
|
|
||||||
};
|
|
||||||
|
|
||||||
img.onerror = () => {
|
|
||||||
this.pesVizHtml = `
|
|
||||||
<div class='alert alert-error' role='alert'>
|
|
||||||
<h4 class='alert-heading'>Could not render PES!</h4>
|
|
||||||
<p>Could not render PES - Do you have access?</p>
|
|
||||||
</div>`;
|
|
||||||
};
|
|
||||||
},
|
|
||||||
|
|
||||||
submit(formId) {
|
|
||||||
const form = document.getElementById(formId);
|
|
||||||
|
|
||||||
// Remove previously injected inputs
|
|
||||||
form.querySelectorAll('.dynamic-param').forEach(el => el.remove());
|
|
||||||
|
|
||||||
// Add values from dynamic form into the html form
|
|
||||||
if (this.formData) {
|
|
||||||
Object.entries(this.formData).forEach(([key, value]) => {
|
|
||||||
const input = document.createElement('input');
|
|
||||||
input.type = 'hidden';
|
|
||||||
input.name = key;
|
|
||||||
input.value = value;
|
|
||||||
input.classList.add('dynamic-param');
|
|
||||||
|
|
||||||
form.appendChild(input);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (form && form.checkValidity()) {
|
|
||||||
this.isSubmitting = true;
|
|
||||||
form.submit();
|
|
||||||
} else if (form) {
|
|
||||||
form.reportValidity();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}"
|
|
||||||
@close="reset()"
|
|
||||||
>
|
|
||||||
<div class="modal-box max-w-3xl">
|
|
||||||
<!-- Header -->
|
|
||||||
<h3 class="text-lg font-bold">New PES</h3>
|
|
||||||
|
|
||||||
<!-- Close button (X) -->
|
|
||||||
<form method="dialog">
|
|
||||||
<button
|
|
||||||
class="btn btn-sm btn-circle btn-ghost absolute top-2 right-2"
|
|
||||||
:disabled="isSubmitting"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<!-- Body -->
|
|
||||||
<div class="py-4">
|
|
||||||
<form
|
|
||||||
id="new-pes-modal-form"
|
|
||||||
accept-charset="UTF-8"
|
|
||||||
action="{% url 'create pes' meta.current_package.uuid %}"
|
|
||||||
method="post"
|
|
||||||
>
|
|
||||||
{% csrf_token %}
|
|
||||||
|
|
||||||
<div class="form-control mb-3">
|
|
||||||
<label class="label" for="compound-name">
|
|
||||||
<span class="label-text">Name</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="compound-name"
|
|
||||||
class="input input-bordered w-full"
|
|
||||||
name="compound-name"
|
|
||||||
placeholder="Name"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-control mb-3">
|
|
||||||
<label class="label" for="compound-description">
|
|
||||||
<span class="label-text">Description</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="compound-description"
|
|
||||||
class="input input-bordered w-full"
|
|
||||||
name="compound-description"
|
|
||||||
placeholder="Description"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-control mb-3">
|
|
||||||
<label class="label" for="pes-link">
|
|
||||||
<span class="label-text">Link to PES</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="pes-link"
|
|
||||||
name="pes-link"
|
|
||||||
type="text"
|
|
||||||
class="input input-bordered w-full"
|
|
||||||
placeholder="Link to PES e.g. https://pesregapp-test.cropkey-np.ag/entities/PES-000126"
|
|
||||||
x-model="pesLink"
|
|
||||||
@input="updatePesViz()"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="pes-viz" class="mb-3" x-html="pesVizHtml"></div>
|
|
||||||
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Footer -->
|
|
||||||
<div class="modal-action">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="btn"
|
|
||||||
onclick="this.closest('dialog').close()"
|
|
||||||
:disabled="isSubmitting"
|
|
||||||
>
|
|
||||||
Close
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="btn btn-primary"
|
|
||||||
@click="submit('new-pes-modal-form')"
|
|
||||||
:disabled="isSubmitting"
|
|
||||||
>
|
|
||||||
<span x-show="!isSubmitting">Submit</span>
|
|
||||||
<span
|
|
||||||
x-show="isSubmitting"
|
|
||||||
class="loading loading-spinner loading-sm"
|
|
||||||
></span>
|
|
||||||
<span x-show="isSubmitting">Creating...</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Backdrop -->
|
|
||||||
<form method="dialog" class="modal-backdrop">
|
|
||||||
<button :disabled="isSubmitting">close</button>
|
|
||||||
</form>
|
|
||||||
</dialog>
|
|
||||||
@ -1,174 +0,0 @@
|
|||||||
{% load static %}
|
|
||||||
|
|
||||||
<dialog
|
|
||||||
id="add_pathway_pes_node_modal"
|
|
||||||
class="modal"
|
|
||||||
x-data="{
|
|
||||||
isSubmitting: false,
|
|
||||||
pesLink: null,
|
|
||||||
pesVizHtml: '',
|
|
||||||
|
|
||||||
reset() {
|
|
||||||
this.isSubmitting = false;
|
|
||||||
},
|
|
||||||
|
|
||||||
get isPESSet() {
|
|
||||||
console.log(this.pesLink);
|
|
||||||
return this.pesLink !== null;
|
|
||||||
},
|
|
||||||
|
|
||||||
updatePesViz() {
|
|
||||||
if (!this.isPESSet) {
|
|
||||||
this.pesVizHtml = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const img = new Image();
|
|
||||||
img.src = '{% url 'depict_pes' %}?pesLink=' + encodeURIComponent(this.pesLink);
|
|
||||||
img.style.width = '100%';
|
|
||||||
img.style.height = '100%';
|
|
||||||
img.style.objectFit = 'cover';
|
|
||||||
|
|
||||||
img.onload = () => {
|
|
||||||
this.pesVizHtml = img.outerHTML;
|
|
||||||
};
|
|
||||||
|
|
||||||
img.onerror = () => {
|
|
||||||
this.pesVizHtml = `
|
|
||||||
<div class='alert alert-error' role='alert'>
|
|
||||||
<h4 class='alert-heading'>Could not render PES!</h4>
|
|
||||||
<p>Could not render PES - Do you have access?</p>
|
|
||||||
</div>`;
|
|
||||||
};
|
|
||||||
},
|
|
||||||
|
|
||||||
submit(formId) {
|
|
||||||
const form = document.getElementById(formId);
|
|
||||||
|
|
||||||
// Remove previously injected inputs
|
|
||||||
form.querySelectorAll('.dynamic-param').forEach(el => el.remove());
|
|
||||||
|
|
||||||
// Add values from dynamic form into the html form
|
|
||||||
if (this.formData) {
|
|
||||||
Object.entries(this.formData).forEach(([key, value]) => {
|
|
||||||
const input = document.createElement('input');
|
|
||||||
input.type = 'hidden';
|
|
||||||
input.name = key;
|
|
||||||
input.value = value;
|
|
||||||
input.classList.add('dynamic-param');
|
|
||||||
|
|
||||||
form.appendChild(input);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (form && form.checkValidity()) {
|
|
||||||
this.isSubmitting = true;
|
|
||||||
form.submit();
|
|
||||||
} else if (form) {
|
|
||||||
form.reportValidity();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}"
|
|
||||||
@close="reset()"
|
|
||||||
>
|
|
||||||
<div class="modal-box max-w-3xl">
|
|
||||||
<!-- Header -->
|
|
||||||
<h3 class="text-lg font-bold">New PES</h3>
|
|
||||||
|
|
||||||
<!-- Close button (X) -->
|
|
||||||
<form method="dialog">
|
|
||||||
<button
|
|
||||||
class="btn btn-sm btn-circle btn-ghost absolute top-2 right-2"
|
|
||||||
:disabled="isSubmitting"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<!-- Body -->
|
|
||||||
<div class="py-4">
|
|
||||||
<form
|
|
||||||
id="new-pes-node-modal-form"
|
|
||||||
accept-charset="UTF-8"
|
|
||||||
action="{% url 'create pes node' current_object.package.uuid current_object.uuid %}"
|
|
||||||
method="post"
|
|
||||||
>
|
|
||||||
{% csrf_token %}
|
|
||||||
|
|
||||||
<div class="form-control mb-3">
|
|
||||||
<label class="label" for="compound-name">
|
|
||||||
<span class="label-text">Name</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="compound-name"
|
|
||||||
class="input input-bordered w-full"
|
|
||||||
name="compound-name"
|
|
||||||
placeholder="Name"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-control mb-3">
|
|
||||||
<label class="label" for="compound-description">
|
|
||||||
<span class="label-text">Description</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="compound-description"
|
|
||||||
class="input input-bordered w-full"
|
|
||||||
name="compound-description"
|
|
||||||
placeholder="Description"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-control mb-3">
|
|
||||||
<label class="label" for="pes-link">
|
|
||||||
<span class="label-text">Link to PES</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="pes-link"
|
|
||||||
name="pes-link"
|
|
||||||
type="text"
|
|
||||||
class="input input-bordered w-full"
|
|
||||||
placeholder="Link to PES e.g. https://pesregapp-test.cropkey-np.ag/entities/PES-000126"
|
|
||||||
x-model="pesLink"
|
|
||||||
@input="updatePesViz()"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="pes-viz" class="mb-3" x-html="pesVizHtml"></div>
|
|
||||||
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Footer -->
|
|
||||||
<div class="modal-action">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="btn"
|
|
||||||
onclick="this.closest('dialog').close()"
|
|
||||||
:disabled="isSubmitting"
|
|
||||||
>
|
|
||||||
Close
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="btn btn-primary"
|
|
||||||
@click="submit('new-pes-node-modal-form')"
|
|
||||||
:disabled="isSubmitting"
|
|
||||||
>
|
|
||||||
<span x-show="!isSubmitting">Submit</span>
|
|
||||||
<span
|
|
||||||
x-show="isSubmitting"
|
|
||||||
class="loading loading-spinner loading-sm"
|
|
||||||
></span>
|
|
||||||
<span x-show="isSubmitting">Creating...</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Backdrop -->
|
|
||||||
<form method="dialog" class="modal-backdrop">
|
|
||||||
<button :disabled="isSubmitting">close</button>
|
|
||||||
</form>
|
|
||||||
</dialog>
|
|
||||||
@ -1,23 +0,0 @@
|
|||||||
{% if compound_structure.pes_link %}
|
|
||||||
<!-- PES -->
|
|
||||||
<div class="collapse-arrow bg-base-200 collapse">
|
|
||||||
<input type="checkbox" checked />
|
|
||||||
<div class="collapse-title text-xl font-medium">Link to PES</div>
|
|
||||||
<div class="collapse-content">
|
|
||||||
<p>
|
|
||||||
<a href="{{ compound_structure.pes_link }}" class="hover:bg-base-200">{{ compound_structure.pes_link }}</a>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Image Representation -->
|
|
||||||
<div class="collapse-arrow bg-base-200 collapse">
|
|
||||||
<input type="checkbox" checked />
|
|
||||||
<div class="collapse-title text-xl font-medium">PES Image Representation</div>
|
|
||||||
<div class="collapse-content">
|
|
||||||
<div class="flex justify-center">
|
|
||||||
<img src='{% url 'depict_pes' %}?pesLink={{ compound_structure.pes_link|urlencode }}'/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
@ -1,23 +0,0 @@
|
|||||||
{% if compound.default_structure.pes_link %}
|
|
||||||
<!-- PES -->
|
|
||||||
<div class="collapse-arrow bg-base-200 collapse">
|
|
||||||
<input type="checkbox" checked />
|
|
||||||
<div class="collapse-title text-xl font-medium">Link to PES</div>
|
|
||||||
<div class="collapse-content">
|
|
||||||
<p>
|
|
||||||
<a href="{{ compound.default_structure.pes_link }}" class="hover:bg-base-200">{{ compound.default_structure.pes_link }}</a>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Image Representation -->
|
|
||||||
<div class="collapse-arrow bg-base-200 collapse">
|
|
||||||
<input type="checkbox" checked />
|
|
||||||
<div class="collapse-title text-xl font-medium">PES Image Representation</div>
|
|
||||||
<div class="collapse-content">
|
|
||||||
<div class="flex justify-center">
|
|
||||||
<img src='{% url 'depict_pes' %}?pesLink={{ compound.default_structure.pes_link|urlencode }}'/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
@ -1,23 +0,0 @@
|
|||||||
{% if node.default_node_label.pes_link %}
|
|
||||||
<!-- PES -->
|
|
||||||
<div class="collapse-arrow bg-base-200 collapse">
|
|
||||||
<input type="checkbox" checked />
|
|
||||||
<div class="collapse-title text-xl font-medium">Link to PES</div>
|
|
||||||
<div class="collapse-content">
|
|
||||||
<p>
|
|
||||||
<a href="{{ node.default_node_label.pes_link }}" class="hover:bg-base-200">{{ node.default_node_label.pes_link }}</a>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Image Representation -->
|
|
||||||
<div class="collapse-arrow bg-base-200 collapse">
|
|
||||||
<input type="checkbox" checked />
|
|
||||||
<div class="collapse-title text-xl font-medium">PES Image Representation</div>
|
|
||||||
<div class="collapse-content">
|
|
||||||
<div class="flex justify-center">
|
|
||||||
<img src='{% url 'depict_pes' %}?pesLink={{ node.default_node_label.pes_link|urlencode }}'/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
@ -1,10 +1,9 @@
|
|||||||
{% extends "framework_modern.html" %}
|
{% extends "framework_modern.html" %}
|
||||||
{% load static %}
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|
||||||
{% block action_modals %}
|
{% block action_modals %}
|
||||||
{% include "modals/objects/edit_package_modal.html" %}
|
{% include "modals/objects/edit_package_modal.html" %}
|
||||||
{% include "modals/objects/view_package_permissions_modal.html" %}
|
|
||||||
{% include "modals/objects/edit_package_permissions_modal.html" %}
|
{% include "modals/objects/edit_package_permissions_modal.html" %}
|
||||||
{% include "modals/objects/publish_package_modal.html" %}
|
{% include "modals/objects/publish_package_modal.html" %}
|
||||||
{% include "modals/objects/set_license_modal.html" %}
|
{% include "modals/objects/set_license_modal.html" %}
|
||||||
@ -17,7 +16,7 @@
|
|||||||
<div class="card bg-base-100">
|
<div class="card bg-base-100">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="flex items-center justify-between">
|
<div class="flex items-center justify-between">
|
||||||
<h2 class="card-title text-2xl">{{ package.name }} {% if meta.url_contains_package and meta.current_package.get_classification_level_display == "Restricted" %}<img src="{% static 'images/restricted_mid.png' %}" width="100">{% elif meta.url_contains_package and meta.current_package.get_classification_level_display == "Secret" %}<img src="{% static 'images/secret_mid.png' %}" width="60">{% endif %}</h2>
|
<h2 class="card-title text-2xl">{{ package.name }} - ({{ package.get_classification_level_display }})</h2>
|
||||||
<div id="actionsButton" class="dropdown dropdown-e nd hidden">
|
<div id="actionsButton" class="dropdown dropdown-e nd hidden">
|
||||||
<div tabindex="0" role="button" class="btn btn-ghost btn-sm">
|
<div tabindex="0" role="button" class="btn btn-ghost btn-sm">
|
||||||
<svg
|
<svg
|
||||||
|
|||||||
@ -1,154 +0,0 @@
|
|||||||
{% extends "static/login_base.html" %}
|
|
||||||
{% load static %}
|
|
||||||
{% block title %}enviPath - Sign In{% endblock %}
|
|
||||||
|
|
||||||
{% block extra_styles %}
|
|
||||||
<style>
|
|
||||||
/* Tab styling */
|
|
||||||
.tab-content {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
.tab-content.active {
|
|
||||||
display: block;
|
|
||||||
}
|
|
||||||
input[type="radio"].tab-radio {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
.tab-label {
|
|
||||||
cursor: pointer;
|
|
||||||
padding: 0.75rem 1.5rem;
|
|
||||||
border-bottom: 2px solid transparent;
|
|
||||||
transition: all 0.3s ease;
|
|
||||||
}
|
|
||||||
.tab-label:hover {
|
|
||||||
background-color: rgba(0, 0, 0, 0.05);
|
|
||||||
}
|
|
||||||
input[type="radio"].tab-radio:checked + .tab-label {
|
|
||||||
border-bottom-color: #3b82f6;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block content %}
|
|
||||||
<div>
|
|
||||||
<img src="{% static 'images/bayer-logo.svg' %}">
|
|
||||||
|
|
||||||
</div>
|
|
||||||
<div class="flex flex-col space-y-4 ...">
|
|
||||||
<div><p></p></div>
|
|
||||||
<div><p></p></div>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Tab Navigation -->
|
|
||||||
<div class="border-base-300 mb-6 border-b" hidden>
|
|
||||||
<div class="flex justify-start">
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
name="auth-tab"
|
|
||||||
id="tab-sso"
|
|
||||||
class="tab-radio"
|
|
||||||
checked
|
|
||||||
/>
|
|
||||||
<label for="tab-sso" class="tab-label">SSO</label>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
name="auth-tab"
|
|
||||||
id="tab-signin"
|
|
||||||
class="tab-radio"
|
|
||||||
/>
|
|
||||||
<label for="tab-signin" class="tab-label">Local User</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- SSO Tab -->
|
|
||||||
<div id="content-sso" class="tab-content active">
|
|
||||||
<button role="link" onclick="window.location.href='/entra/login'" name="sso" class="btn btn-primary w-full">
|
|
||||||
Login with Microsoft
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Sign In Tab -->
|
|
||||||
<div id="content-signin" class="tab-content">
|
|
||||||
<form method="post" action="{% url 'login' %}" class="space-y-4">
|
|
||||||
{% csrf_token %}
|
|
||||||
<input type="hidden" name="login" value="true" />
|
|
||||||
|
|
||||||
<div class="form-control">
|
|
||||||
<label class="label" for="username">
|
|
||||||
<span class="label-text">Account</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
id="username"
|
|
||||||
name="username"
|
|
||||||
placeholder="Username or Email"
|
|
||||||
class="input input-bordered w-full"
|
|
||||||
required
|
|
||||||
autocomplete="username"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-control">
|
|
||||||
<label class="label" for="passwordinput">
|
|
||||||
<span class="label-text">Password</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
id="passwordinput"
|
|
||||||
name="password"
|
|
||||||
placeholder="••••••••"
|
|
||||||
class="input input-bordered w-full"
|
|
||||||
required
|
|
||||||
autocomplete="current-password"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="text-right">
|
|
||||||
<a href="{% url 'password_reset' %}" class="link link-primary text-sm"
|
|
||||||
>Forgot password?</a
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<input type="hidden" name="next" value="{{ next }}" />
|
|
||||||
|
|
||||||
<button type="submit" name="signin" class="btn btn-primary w-full">
|
|
||||||
Sign In
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{% endblock %}
|
|
||||||
|
|
||||||
{% block extra_scripts %}
|
|
||||||
<script>
|
|
||||||
// Tab switching functionality
|
|
||||||
document.querySelectorAll('input[name="auth-tab"]').forEach((radio) => {
|
|
||||||
radio.addEventListener("change", function () {
|
|
||||||
// Hide all content
|
|
||||||
document.querySelectorAll(".tab-content").forEach((content) => {
|
|
||||||
content.classList.remove("active");
|
|
||||||
});
|
|
||||||
|
|
||||||
// Show selected content
|
|
||||||
const contentId = "content-" + this.id.replace("tab-", "");
|
|
||||||
document.getElementById(contentId).classList.add("active");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Check for hash in URL to auto-select tab
|
|
||||||
window.addEventListener("DOMContentLoaded", function () {
|
|
||||||
const hash = window.location.hash.substring(1); // Remove the # symbol
|
|
||||||
if (hash === "signup" || hash === "signin") {
|
|
||||||
const tabRadio = document.getElementById("tab-" + hash);
|
|
||||||
if (tabRadio) {
|
|
||||||
tabRadio.checked = true;
|
|
||||||
// Trigger change event to show correct content
|
|
||||||
tabRadio.dispatchEvent(new Event("change"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
{% endblock %}
|
|
||||||
@ -1,19 +0,0 @@
|
|||||||
from django.urls import re_path
|
|
||||||
|
|
||||||
from . import views as v
|
|
||||||
|
|
||||||
UUID = "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"
|
|
||||||
|
|
||||||
urlpatterns = [
|
|
||||||
re_path(r"^depict_pes$", v.visualize_pes, name="depict_pes"),
|
|
||||||
re_path(
|
|
||||||
rf"^package/(?P<package_uuid>{UUID})/pes$",
|
|
||||||
v.create_pes,
|
|
||||||
name="create pes",
|
|
||||||
),
|
|
||||||
re_path(
|
|
||||||
rf"^package/(?P<package_uuid>{UUID})/pathway/(?P<pathway_uuid>{UUID})/pes$",
|
|
||||||
v.create_pes_node,
|
|
||||||
name="create pes node",
|
|
||||||
),
|
|
||||||
]
|
|
||||||
226
bayer/views.py
@ -1,225 +1,3 @@
|
|||||||
import base64
|
from django.shortcuts import render
|
||||||
|
|
||||||
import requests
|
# Create your views here.
|
||||||
from django.conf import settings as s
|
|
||||||
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed
|
|
||||||
from django.shortcuts import redirect
|
|
||||||
|
|
||||||
from bayer.models import PESCompound
|
|
||||||
from epdb.logic import PackageManager
|
|
||||||
from epdb.models import Pathway, Node
|
|
||||||
from epdb.views import _anonymous_or_real, error
|
|
||||||
from utilities.decorators import package_permission_required
|
|
||||||
|
|
||||||
Package = s.GET_PACKAGE_MODEL()
|
|
||||||
|
|
||||||
|
|
||||||
@package_permission_required()
|
|
||||||
def create_pes(request, package_uuid):
|
|
||||||
current_user = _anonymous_or_real(request)
|
|
||||||
current_package = PackageManager.get_package_by_id(current_user, package_uuid)
|
|
||||||
|
|
||||||
if request.method == "POST":
|
|
||||||
|
|
||||||
if current_package.classification_level == Package.Classification.INTERNAL:
|
|
||||||
return error(
|
|
||||||
request,
|
|
||||||
f'Creation of PESs for package {current_package.name} failed!',
|
|
||||||
"Creating PESs for internal packages is not allowed.",
|
|
||||||
)
|
|
||||||
|
|
||||||
compound_name = request.POST.get('compound-name')
|
|
||||||
compound_description = request.POST.get('compound-description')
|
|
||||||
pes_link = request.POST.get('pes-link')
|
|
||||||
|
|
||||||
if pes_link:
|
|
||||||
try:
|
|
||||||
pes_data = fetch_pes(request, pes_link)
|
|
||||||
except ValueError as e:
|
|
||||||
return error(
|
|
||||||
request,
|
|
||||||
"Could not fetch PES",
|
|
||||||
f"Could not fetch PES data for {pes_link}"
|
|
||||||
)
|
|
||||||
|
|
||||||
classification = pes_data.get("classificationLevel", "")
|
|
||||||
if "secret" == classification.lower():
|
|
||||||
|
|
||||||
if current_package.classification_level != Package.Classification.SECRET:
|
|
||||||
return error(
|
|
||||||
request,
|
|
||||||
"Classification Mismatch!",
|
|
||||||
"Cannot create secret PESs in non-secret packages."
|
|
||||||
)
|
|
||||||
|
|
||||||
data_pools = pes_data.get("dataPools")
|
|
||||||
if data_pools:
|
|
||||||
if (current_package.data_pool.name not in s.DATA_POOL_MAPPING
|
|
||||||
or s.DATA_POOL_MAPPING[current_package.data_pool.name] not in data_pools):
|
|
||||||
|
|
||||||
if current_package.data_pool.name not in s.DATA_POOL_MAPPING:
|
|
||||||
detail = f"Data pool {current_package.data_pool.name} not found in Mapping."
|
|
||||||
else:
|
|
||||||
detail = f"PES data pool {s.DATA_POOL_MAPPING[current_package.data_pool.name]} not found in PES data"
|
|
||||||
|
|
||||||
return error(
|
|
||||||
request,
|
|
||||||
"Invalid PES data",
|
|
||||||
detail
|
|
||||||
)
|
|
||||||
|
|
||||||
pes = PESCompound.create(current_package, pes_data, compound_name, compound_description)
|
|
||||||
|
|
||||||
return redirect(pes.url)
|
|
||||||
else:
|
|
||||||
return error(
|
|
||||||
request,
|
|
||||||
"No PES link received",
|
|
||||||
"Please provide a PES link."
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
return HttpResponseNotAllowed(["POST"])
|
|
||||||
|
|
||||||
|
|
||||||
@package_permission_required()
|
|
||||||
def create_pes_node(request, package_uuid, pathway_uuid):
|
|
||||||
current_user = _anonymous_or_real(request)
|
|
||||||
current_package = PackageManager.get_package_by_id(current_user, package_uuid)
|
|
||||||
current_pathway = Pathway.objects.get(package=current_package, uuid=pathway_uuid)
|
|
||||||
|
|
||||||
if request.method == "POST":
|
|
||||||
|
|
||||||
if current_package.classification_level == Package.Classification.INTERNAL:
|
|
||||||
return error(
|
|
||||||
request,
|
|
||||||
f'Creation of PESs for package {current_package.name} failed!',
|
|
||||||
"Creating PESs for internal packages is not allowed.",
|
|
||||||
)
|
|
||||||
|
|
||||||
compound_name = request.POST.get('compound-name')
|
|
||||||
compound_description = request.POST.get('compound-description')
|
|
||||||
pes_link = request.POST.get('pes-link')
|
|
||||||
|
|
||||||
if pes_link:
|
|
||||||
try:
|
|
||||||
pes_data = fetch_pes(request, pes_link)
|
|
||||||
except ValueError as e:
|
|
||||||
return error(
|
|
||||||
request,
|
|
||||||
"Could not fetch PES",
|
|
||||||
f"Could not fetch PES data for {pes_link}"
|
|
||||||
)
|
|
||||||
|
|
||||||
classification = pes_data.get("classificationLevel", "")
|
|
||||||
if "secret" == classification.lower():
|
|
||||||
|
|
||||||
if current_package.classification_level != Package.Classification.SECRET:
|
|
||||||
return error(
|
|
||||||
request,
|
|
||||||
"Classification Mismatch!",
|
|
||||||
"Cannot create secret PESs in non-secret packages."
|
|
||||||
)
|
|
||||||
|
|
||||||
data_pools = pes_data.get("dataPools")
|
|
||||||
if data_pools:
|
|
||||||
if (current_package.data_pool.name not in s.DATA_POOL_MAPPING
|
|
||||||
or s.DATA_POOL_MAPPING[current_package.data_pool.name] not in data_pools):
|
|
||||||
|
|
||||||
if current_package.data_pool.name not in s.DATA_POOL_MAPPING:
|
|
||||||
detail = f"Data pool {current_package.data_pool.name} not found in Mapping."
|
|
||||||
else:
|
|
||||||
detail = f"PES data pool {s.DATA_POOL_MAPPING[current_package.data_pool.name]} not found in PES data"
|
|
||||||
|
|
||||||
return error(
|
|
||||||
request,
|
|
||||||
"Invalid PES data",
|
|
||||||
detail
|
|
||||||
)
|
|
||||||
|
|
||||||
pes = PESCompound.create(current_package, pes_data, compound_name, compound_description)
|
|
||||||
|
|
||||||
node_qs = Node.objects.filter(
|
|
||||||
pathway=current_pathway,
|
|
||||||
default_node_label=pes.default_structure
|
|
||||||
)
|
|
||||||
|
|
||||||
if node_qs.exists():
|
|
||||||
return redirect(current_pathway.url)
|
|
||||||
|
|
||||||
n = Node()
|
|
||||||
n.stereo_removed = False
|
|
||||||
n.pathway = current_pathway
|
|
||||||
n.depth = 0
|
|
||||||
|
|
||||||
n.default_node_label = pes.default_structure
|
|
||||||
n.save()
|
|
||||||
|
|
||||||
n.node_labels.add(pes.default_structure)
|
|
||||||
n.save()
|
|
||||||
|
|
||||||
return redirect(current_pathway.url)
|
|
||||||
|
|
||||||
else:
|
|
||||||
return error(
|
|
||||||
request,
|
|
||||||
"No PES link received",
|
|
||||||
"Please provide a PES link."
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
return HttpResponseNotAllowed(["POST"])
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_pes(request, pes_url) -> dict:
|
|
||||||
from epauth.views import get_access_token_from_request
|
|
||||||
token = get_access_token_from_request(request)
|
|
||||||
|
|
||||||
if token is None:
|
|
||||||
token = pes_url.split('/')[-1] == 'dummy'
|
|
||||||
|
|
||||||
if token:
|
|
||||||
for k, v in s.PES_API_MAPPING.items():
|
|
||||||
if pes_url.startswith(k):
|
|
||||||
pes_id = pes_url.split('/')[-1]
|
|
||||||
|
|
||||||
if pes_id == 'dummy':
|
|
||||||
import json
|
|
||||||
res_data = json.load(open(s.BASE_DIR / "fixtures/pes.json"))
|
|
||||||
res_data["pes_url"] = pes_url
|
|
||||||
return res_data
|
|
||||||
else:
|
|
||||||
headers = {"Authorization": f"Bearer {token['access_token']}"}
|
|
||||||
params = {"pes_reg_entity_corporate_id": pes_id}
|
|
||||||
|
|
||||||
res = requests.get(v, headers=headers, params=params, proxies=s.PROXIES or None)
|
|
||||||
|
|
||||||
try:
|
|
||||||
res.raise_for_status()
|
|
||||||
pes_data = res.json()
|
|
||||||
|
|
||||||
if len(pes_data) == 0:
|
|
||||||
raise ValueError(f"PES with id {pes_id} not found")
|
|
||||||
|
|
||||||
res_data = pes_data[0]
|
|
||||||
res_data["pes_url"] = pes_url
|
|
||||||
return res_data
|
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
|
||||||
raise ValueError(f"Error fetching PES with id {pes_id}: {e}")
|
|
||||||
else:
|
|
||||||
raise ValueError(f"Unknown URL {pes_url}")
|
|
||||||
else:
|
|
||||||
raise ValueError("Could not fetch access token from request.")
|
|
||||||
|
|
||||||
|
|
||||||
def visualize_pes(request):
|
|
||||||
pes_link = request.GET.get('pesLink')
|
|
||||||
|
|
||||||
if pes_link:
|
|
||||||
pes_data = fetch_pes(request, pes_link)
|
|
||||||
|
|
||||||
representations = pes_data.get('representations')
|
|
||||||
|
|
||||||
for rep in representations:
|
|
||||||
if rep.get('type') == 'color':
|
|
||||||
image_data = base64.b64decode(rep.get('base64').replace("data:image/png;base64,", ""))
|
|
||||||
return HttpResponse(image_data, content_type="image/png")
|
|
||||||
|
|||||||
198
bb4g/__init__.py
@ -1,198 +0,0 @@
|
|||||||
import enum
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import math
|
|
||||||
from datetime import datetime
|
|
||||||
from typing import List
|
|
||||||
|
|
||||||
import requests
|
|
||||||
from django.conf import settings as s
|
|
||||||
from envipy_additional_information import register, EnviPyModel, UIConfig, WidgetType
|
|
||||||
|
|
||||||
from bridge.contracts import Classifier # noqa: I001
|
|
||||||
from bridge.dto import (
|
|
||||||
BuildResult,
|
|
||||||
EnviPyDTO,
|
|
||||||
EvaluationResult,
|
|
||||||
RunResult,
|
|
||||||
TransformationProductPrediction,
|
|
||||||
) # noqa: I001
|
|
||||||
|
|
||||||
logger = logging.getLogger("epdb")
|
|
||||||
|
|
||||||
|
|
||||||
class SamplingAlgorithm(enum.Enum):
|
|
||||||
EXACT = "exact"
|
|
||||||
|
|
||||||
|
|
||||||
@register("bb4gconfig")
|
|
||||||
class BB4GConfig(EnviPyModel):
|
|
||||||
sampling_algorithm: SamplingAlgorithm = SamplingAlgorithm.EXACT
|
|
||||||
cutoff: int = -5
|
|
||||||
|
|
||||||
class UI:
|
|
||||||
title = "BB4G Configuration"
|
|
||||||
sampling_algorithm = UIConfig(
|
|
||||||
widget=WidgetType.SELECT,
|
|
||||||
label="BB4G Sampling Algorithm",
|
|
||||||
order=1,
|
|
||||||
placeholder="If unset defaults to 'exact'"
|
|
||||||
)
|
|
||||||
cutoff = UIConfig(
|
|
||||||
widget=WidgetType.NUMBER,
|
|
||||||
label="BB4G Cutoff",
|
|
||||||
order=2,
|
|
||||||
placeholder="If unset defaults to -5"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# Once stable these will be exposed by enviPy-plugins lib
|
|
||||||
class BB4G(Classifier):
|
|
||||||
Config = BB4GConfig
|
|
||||||
|
|
||||||
def __init__(self, config: BB4GConfig | None = None):
|
|
||||||
super().__init__(config)
|
|
||||||
self.url = f"{s.BB4G_URL}"
|
|
||||||
|
|
||||||
self.token = self.acquire_token()
|
|
||||||
self.header = {
|
|
||||||
"Authorization": f"Bearer {self.token}",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
}
|
|
||||||
|
|
||||||
def acquire_token(self):
|
|
||||||
BB4G_TENANT_ID = s.BB4G_TENANT_ID
|
|
||||||
BB4G_CLIENT_ID = s.BB4G_CLIENT_ID
|
|
||||||
BB4G_CLIENT_SECRET = s.BB4G_CLIENT_SECRET
|
|
||||||
BB4G_SCOPE = s.BB4G_SCOPE
|
|
||||||
|
|
||||||
BB4G_TOKEN_URL = f"https://login.microsoftonline.com/{BB4G_TENANT_ID}/oauth2/v2.0/token"
|
|
||||||
|
|
||||||
payload = {
|
|
||||||
"client_id": BB4G_CLIENT_ID,
|
|
||||||
"client_secret": BB4G_CLIENT_SECRET,
|
|
||||||
"scope": BB4G_SCOPE,
|
|
||||||
"grant_type": "client_credentials"
|
|
||||||
}
|
|
||||||
|
|
||||||
# No Proxy required, URL is whitelisted
|
|
||||||
res = requests.post(BB4G_TOKEN_URL, data=payload)
|
|
||||||
|
|
||||||
res.raise_for_status()
|
|
||||||
|
|
||||||
return res.json()["access_token"]
|
|
||||||
|
|
||||||
def start(self):
|
|
||||||
header = {
|
|
||||||
"Authorization": f"Bearer {self.token}",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
}
|
|
||||||
|
|
||||||
started = False
|
|
||||||
|
|
||||||
while not started:
|
|
||||||
res = requests.post(f"{self.url}/start", headers=header, data={}, proxies=s.PROXIES or None)
|
|
||||||
logger.info(f"Starting BB4G: {res.status_code}")
|
|
||||||
if res.status_code == 200:
|
|
||||||
started = True
|
|
||||||
elif res.status_code in [500, 502]:
|
|
||||||
import time
|
|
||||||
time.sleep(5)
|
|
||||||
else:
|
|
||||||
raise ValueError(f"Unexpected status code: {res.status_code}")
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def requires_rule_packages(cls) -> bool:
|
|
||||||
return False
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def requires_data_packages(cls) -> bool:
|
|
||||||
return False
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def identifier(cls) -> str:
|
|
||||||
return "bb4g"
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def name(cls) -> str:
|
|
||||||
return "BB4G Template Free Model"
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def display(cls) -> str:
|
|
||||||
return "BB4G Template Free Model"
|
|
||||||
|
|
||||||
def build(self, eP: EnviPyDTO, *args, **kwargs) -> BuildResult | None:
|
|
||||||
return
|
|
||||||
|
|
||||||
def run(self, eP: EnviPyDTO, *args, **kwargs) -> RunResult:
|
|
||||||
|
|
||||||
# Ensure Service is running
|
|
||||||
self.start()
|
|
||||||
|
|
||||||
smiles = [c.smiles for c in eP.get_compounds()]
|
|
||||||
preds = self._post(smiles)
|
|
||||||
|
|
||||||
results = []
|
|
||||||
|
|
||||||
for substrate in preds.keys():
|
|
||||||
results.append(
|
|
||||||
TransformationProductPrediction(
|
|
||||||
substrate=substrate,
|
|
||||||
products=preds[substrate],
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
return RunResult(
|
|
||||||
producer=eP.get_context().url,
|
|
||||||
description=f"Generated at {datetime.now()}",
|
|
||||||
result=results,
|
|
||||||
)
|
|
||||||
|
|
||||||
def evaluate(self, eP: EnviPyDTO, *args, **kwargs) -> EvaluationResult:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def build_and_evaluate(self, eP: EnviPyDTO, *args, **kwargs) -> EvaluationResult:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def _post(self, smiles: List[str]) -> dict[str, dict[str, float]]:
|
|
||||||
header = {
|
|
||||||
"Authorization": f"Bearer {self.token}",
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
}
|
|
||||||
|
|
||||||
result = {}
|
|
||||||
|
|
||||||
for smi in smiles:
|
|
||||||
data = {
|
|
||||||
"smiles": smi,
|
|
||||||
"sampling_alg": self.config.sampling_algorithm.value,
|
|
||||||
"cutoff": self.config.cutoff,
|
|
||||||
}
|
|
||||||
|
|
||||||
retries = 0
|
|
||||||
while retries < 100:
|
|
||||||
resp = requests.post(f"{self.url}/compute", headers=header, data=json.dumps(data),
|
|
||||||
proxies=s.PROXIES or None)
|
|
||||||
|
|
||||||
if resp.status_code == 418:
|
|
||||||
retries += 1
|
|
||||||
logger.info(f"BB4G predict hit a 418, retrying in 60 seconds")
|
|
||||||
import time
|
|
||||||
time.sleep(3)
|
|
||||||
continue
|
|
||||||
|
|
||||||
resp.raise_for_status()
|
|
||||||
|
|
||||||
for substrate, predictions in resp.json().items():
|
|
||||||
preds = {}
|
|
||||||
|
|
||||||
for pred in predictions:
|
|
||||||
prod = pred["prediction"]
|
|
||||||
prob = math.exp(pred["log_likelihood"])
|
|
||||||
preds[prod] = prob
|
|
||||||
|
|
||||||
result[substrate] = preds
|
|
||||||
|
|
||||||
break
|
|
||||||
|
|
||||||
return result
|
|
||||||
@ -254,14 +254,7 @@ class Classifier(Plugin):
|
|||||||
def parse_config(cls, data: dict | None = None) -> EnviPyModel | None:
|
def parse_config(cls, data: dict | None = None) -> EnviPyModel | None:
|
||||||
if cls.Config is None:
|
if cls.Config is None:
|
||||||
return None
|
return None
|
||||||
|
return cls.Config(**(data or {}))
|
||||||
# remove empty strings a.k.a unset params to not overwrite defaults
|
|
||||||
cpy = {}
|
|
||||||
if data is not None:
|
|
||||||
for k, v in data.items():
|
|
||||||
if v != "":
|
|
||||||
cpy[k] = v
|
|
||||||
return cls.Config(**cpy)
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def create(cls, data: dict | None = None):
|
def create(cls, data: dict | None = None):
|
||||||
|
|||||||
@ -25,14 +25,25 @@ services:
|
|||||||
- ep_bayer_redis_data:/data
|
- ep_bayer_redis_data:/data
|
||||||
|
|
||||||
biotransformer3:
|
biotransformer3:
|
||||||
image: git.envipath.com/envipath/biotransformer3:1.0
|
image: envipath/biotransformer3:1.0
|
||||||
container_name: epbiotransformer3
|
container_name: epbiotransformer3
|
||||||
|
|
||||||
|
# web:
|
||||||
|
# image: envipath/envipy-bayer:1.0
|
||||||
|
# container_name: epdjango
|
||||||
|
# ports:
|
||||||
|
# - "127.0.0.1:8000:8000"
|
||||||
|
# env_file:
|
||||||
|
# - .env
|
||||||
|
# command: gunicorn envipath.wsgi:application --bind 0.0.0.0:8000 --workers 3
|
||||||
|
# volumes:
|
||||||
|
# - ep_bayer_data:/opt/enviPy/
|
||||||
|
|
||||||
celery_worker:
|
celery_worker:
|
||||||
image: git.envipath.com/envipath/envipy-bayer:1.2
|
image: envipath/envipy-bayer:1.0
|
||||||
container_name: epcelery
|
container_name: epcelery
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env.dev
|
||||||
command: celery -A envipath worker --concurrency=6 -Q model,predict,background --pool threads
|
command: celery -A envipath worker --concurrency=6 -Q model,predict,background --pool threads
|
||||||
volumes:
|
volumes:
|
||||||
- ep_bayer_data:/opt/enviPy/
|
- ep_bayer_data:/opt/enviPy/
|
||||||
|
|||||||
@ -143,12 +143,6 @@ if os.environ.get("USE_TEMPLATE_DB", False) == "True":
|
|||||||
"TEMPLATE": os.environ["TEMPLATE_DB"],
|
"TEMPLATE": os.environ["TEMPLATE_DB"],
|
||||||
}
|
}
|
||||||
|
|
||||||
CACHES = {
|
|
||||||
"default": {
|
|
||||||
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
|
|
||||||
"LOCATION": "unique-snowflake",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Password validation
|
# Password validation
|
||||||
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
|
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
|
||||||
@ -275,12 +269,6 @@ LOGGING = {
|
|||||||
"filename": os.path.join(LOG_DIR, "debug.log"),
|
"filename": os.path.join(LOG_DIR, "debug.log"),
|
||||||
"formatter": "simple",
|
"formatter": "simple",
|
||||||
},
|
},
|
||||||
"auth_file": {
|
|
||||||
"level": "INFO", # Or higher
|
|
||||||
"class": "logging.FileHandler",
|
|
||||||
"filename": os.path.join(LOG_DIR, "auth.log"),
|
|
||||||
"formatter": "simple",
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"loggers": {
|
"loggers": {
|
||||||
# For everything under epdb/ loaded via getlogger(__name__)
|
# For everything under epdb/ loaded via getlogger(__name__)
|
||||||
@ -301,11 +289,6 @@ LOGGING = {
|
|||||||
"propagate": True,
|
"propagate": True,
|
||||||
"level": os.environ.get("LOG_LEVEL", "INFO"),
|
"level": os.environ.get("LOG_LEVEL", "INFO"),
|
||||||
},
|
},
|
||||||
"auth": {
|
|
||||||
"handlers": ["auth_file"],
|
|
||||||
"propagate": True,
|
|
||||||
"level": os.environ.get("LOG_LEVEL", "INFO"),
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -354,7 +337,7 @@ DEFAULT_MODEL_PARAMS = {
|
|||||||
"num_chains": 10,
|
"num_chains": 10,
|
||||||
}
|
}
|
||||||
|
|
||||||
DEFAULT_MAX_NUMBER_OF_NODES = 9999
|
DEFAULT_MAX_NUMBER_OF_NODES = 50
|
||||||
DEFAULT_MAX_DEPTH = 8
|
DEFAULT_MAX_DEPTH = 8
|
||||||
DEFAULT_MODEL_THRESHOLD = 0.25
|
DEFAULT_MODEL_THRESHOLD = 0.25
|
||||||
|
|
||||||
@ -468,39 +451,5 @@ if PES_API_MAPPING:
|
|||||||
else:
|
else:
|
||||||
PES_API_MAPPING = {}
|
PES_API_MAPPING = {}
|
||||||
|
|
||||||
# Entra Groups
|
# AD Group Mapping
|
||||||
ENTRA_GROUPS = os.environ.get("ENTRA_GROUPS", None)
|
|
||||||
if ENTRA_GROUPS:
|
|
||||||
import json
|
|
||||||
ENTRA_GROUPS = json.loads(ENTRA_GROUPS)
|
|
||||||
else:
|
|
||||||
ENTRA_GROUPS = {}
|
|
||||||
|
|
||||||
ENTRA_SECRET_GROUPS = os.environ.get("ENTRA_SECRET_GROUPS", None)
|
|
||||||
if ENTRA_SECRET_GROUPS:
|
|
||||||
import json
|
|
||||||
ENTRA_SECRET_GROUPS = json.loads(ENTRA_SECRET_GROUPS)
|
|
||||||
else:
|
|
||||||
ENTRA_SECRET_GROUPS = {}
|
|
||||||
|
|
||||||
# PES Data Pools vs Entra Mapping
|
|
||||||
DATA_POOL_MAPPING = os.environ.get("DATA_POOL_MAPPING", None)
|
|
||||||
if DATA_POOL_MAPPING:
|
|
||||||
import json
|
|
||||||
DATA_POOL_MAPPING = json.loads(DATA_POOL_MAPPING)
|
|
||||||
else:
|
|
||||||
DATA_POOL_MAPPING = {}
|
|
||||||
|
|
||||||
PROXIES = {}
|
|
||||||
if os.environ.get("HTTP_PROXY"):
|
|
||||||
PROXIES["http"] = os.environ.get("HTTP_PROXY")
|
|
||||||
PROXIES["https"] = os.environ.get("HTTPS_PROXY")
|
|
||||||
|
|
||||||
# BB4g
|
|
||||||
BB4G_URL = os.environ.get("BB4G_URL")
|
|
||||||
BB4G_TENANT_ID = os.environ.get("BB4G_TENANT_ID")
|
|
||||||
BB4G_CLIENT_ID = os.environ.get("BB4G_CLIENT_ID")
|
|
||||||
BB4G_CLIENT_SECRET = os.environ.get("BB4G_CLIENT_SECRET")
|
|
||||||
BB4G_SCOPE = os.environ.get("BB4G_SCOPE")
|
|
||||||
|
|
||||||
os.environ["NO_PROXY"] = "localhost,127.0.0.1,epbiotransformer3"
|
|
||||||
@ -40,9 +40,6 @@ if "migration" in s.INSTALLED_APPS:
|
|||||||
if s.MS_ENTRA_ENABLED:
|
if s.MS_ENTRA_ENABLED:
|
||||||
urlpatterns.append(path(f"{PATH_PREFIX}", include("epauth.urls")))
|
urlpatterns.append(path(f"{PATH_PREFIX}", include("epauth.urls")))
|
||||||
|
|
||||||
if s.TENANT != "public":
|
|
||||||
urlpatterns.append(path(f"{PATH_PREFIX}", include(f"{s.TENANT}.urls")))
|
|
||||||
|
|
||||||
# Custom error handlers
|
# Custom error handlers
|
||||||
handler400 = "epdb.views.handler400"
|
handler400 = "epdb.views.handler400"
|
||||||
handler403 = "epdb.views.handler403"
|
handler403 = "epdb.views.handler403"
|
||||||
|
|||||||
@ -117,28 +117,25 @@ class APIPermissionTestBase(TestCase):
|
|||||||
|
|
||||||
# Create test compounds in each package
|
# Create test compounds in each package
|
||||||
cls.reviewed_compound = Compound.create(
|
cls.reviewed_compound = Compound.create(
|
||||||
cls.reviewed_package, "C", name="Reviewed Compound", description="Test compound"
|
cls.reviewed_package, "C", "Reviewed Compound", "Test compound"
|
||||||
)
|
)
|
||||||
cls.owned_compound = Compound.create(
|
cls.owned_compound = Compound.create(
|
||||||
cls.unreviewed_package_owned, "CC", name="Owned Compound", description="Test compound"
|
cls.unreviewed_package_owned, "CC", "Owned Compound", "Test compound"
|
||||||
)
|
)
|
||||||
cls.read_compound = Compound.create(
|
cls.read_compound = Compound.create(
|
||||||
cls.unreviewed_package_read, "CCC", name="Read Compound", description="Test compound"
|
cls.unreviewed_package_read, "CCC", "Read Compound", "Test compound"
|
||||||
)
|
)
|
||||||
cls.write_compound = Compound.create(
|
cls.write_compound = Compound.create(
|
||||||
cls.unreviewed_package_write, "CCCC", name="Write Compound", description="Test compound"
|
cls.unreviewed_package_write, "CCCC", "Write Compound", "Test compound"
|
||||||
)
|
)
|
||||||
cls.all_compound = Compound.create(
|
cls.all_compound = Compound.create(
|
||||||
cls.unreviewed_package_all, "CCCCC", name="All Compound", description="Test compound"
|
cls.unreviewed_package_all, "CCCCC", "All Compound", "Test compound"
|
||||||
)
|
)
|
||||||
cls.no_access_compound = Compound.create(
|
cls.no_access_compound = Compound.create(
|
||||||
cls.unreviewed_package_no_access,
|
cls.unreviewed_package_no_access, "CCCCCC", "No Access Compound", "Test compound"
|
||||||
"CCCCCC",
|
|
||||||
name="No Access Compound",
|
|
||||||
description="Test compound",
|
|
||||||
)
|
)
|
||||||
cls.group_compound = Compound.create(
|
cls.group_compound = Compound.create(
|
||||||
cls.group_package, "CCCCCCC", name="Group Compound", description="Test compound"
|
cls.group_package, "CCCCCCC", "Group Compound", "Test compound"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -294,8 +294,8 @@ class CompoundPaginationAPITest(BaseTestAPIGetPaginated, TestCase):
|
|||||||
return Compound.create(
|
return Compound.create(
|
||||||
package,
|
package,
|
||||||
smiles,
|
smiles,
|
||||||
name=f"Reviewed Compound {idx:03d}",
|
f"Reviewed Compound {idx:03d}",
|
||||||
description="Compound for pagination tests",
|
"Compound for pagination tests",
|
||||||
)
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -305,8 +305,8 @@ class CompoundPaginationAPITest(BaseTestAPIGetPaginated, TestCase):
|
|||||||
return Compound.create(
|
return Compound.create(
|
||||||
package,
|
package,
|
||||||
smiles,
|
smiles,
|
||||||
name=f"Draft Compound {idx:03d}",
|
f"Draft Compound {idx:03d}",
|
||||||
description="Compound for pagination tests",
|
"Compound for pagination tests",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -1,26 +0,0 @@
|
|||||||
from django.conf import settings as s
|
|
||||||
from ninja import Router
|
|
||||||
from ninja_extra.pagination import paginate
|
|
||||||
|
|
||||||
from epdb.models import JobLog
|
|
||||||
from ..pagination import EnhancedPageNumberPagination
|
|
||||||
from ..schemas import JobLogOutSchema
|
|
||||||
|
|
||||||
router = Router()
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/joblog/", response=EnhancedPageNumberPagination.Output[JobLogOutSchema])
|
|
||||||
@paginate(
|
|
||||||
EnhancedPageNumberPagination,
|
|
||||||
page_size=s.API_PAGINATION_DEFAULT_PAGE_SIZE,
|
|
||||||
)
|
|
||||||
def list_all_joblogs(request):
|
|
||||||
"""
|
|
||||||
List all JobLogs from reviewed packages.
|
|
||||||
"""
|
|
||||||
current_user = request.user
|
|
||||||
|
|
||||||
if current_user.is_superuser:
|
|
||||||
return JobLog.objects.all().order_by("-created")
|
|
||||||
else:
|
|
||||||
return JobLog.objects.filter(user=current_user).order_by("-created")
|
|
||||||
@ -15,7 +15,6 @@ from .endpoints import (
|
|||||||
additional_information,
|
additional_information,
|
||||||
settings,
|
settings,
|
||||||
groups,
|
groups,
|
||||||
joblogs,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Main router with authentication
|
# Main router with authentication
|
||||||
@ -38,7 +37,6 @@ router.add_router("", structure.router)
|
|||||||
router.add_router("", additional_information.router)
|
router.add_router("", additional_information.router)
|
||||||
router.add_router("", settings.router)
|
router.add_router("", settings.router)
|
||||||
router.add_router("", groups.router)
|
router.add_router("", groups.router)
|
||||||
router.add_router("", joblogs.router)
|
|
||||||
|
|
||||||
if s.IUCLID_EXPORT_ENABLED:
|
if s.IUCLID_EXPORT_ENABLED:
|
||||||
from epiuclid.api import router as iuclid_router
|
from epiuclid.api import router as iuclid_router
|
||||||
|
|||||||
@ -1,10 +1,7 @@
|
|||||||
from datetime import datetime
|
from ninja import FilterSchema, FilterLookup, Schema
|
||||||
from typing import Annotated, Optional, List, Dict, Any
|
from typing import Annotated, Optional, List, Dict, Any
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from django.urls import reverse
|
|
||||||
from ninja import Field, FilterSchema, FilterLookup, Schema
|
|
||||||
|
|
||||||
|
|
||||||
# Filter schema for query parameters
|
# Filter schema for query parameters
|
||||||
class ReviewStatusFilter(FilterSchema):
|
class ReviewStatusFilter(FilterSchema):
|
||||||
@ -136,23 +133,3 @@ class GroupOutSchema(Schema):
|
|||||||
url: str = ""
|
url: str = ""
|
||||||
name: str
|
name: str
|
||||||
description: str
|
description: str
|
||||||
|
|
||||||
|
|
||||||
class SimpleUserOutSchema(Schema):
|
|
||||||
uuid: UUID
|
|
||||||
url: str
|
|
||||||
name: str = Field(alias="username")
|
|
||||||
|
|
||||||
|
|
||||||
class JobLogOutSchema(Schema):
|
|
||||||
user: SimpleUserOutSchema
|
|
||||||
id: UUID = Field(alias="task_id")
|
|
||||||
url: str
|
|
||||||
name: str = Field(alias="job_name")
|
|
||||||
created: datetime = Field(alias="created")
|
|
||||||
status: str = Field(alias="status")
|
|
||||||
done: Optional[datetime] = Field(None, alias="done_at")
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def resolve_url(obj):
|
|
||||||
return reverse("job detail", kwargs={"job_uuid": obj.task_id})
|
|
||||||
|
|||||||
@ -5,5 +5,4 @@ from . import views
|
|||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path("entra/login/", views.entra_login, name="entra_login"),
|
path("entra/login/", views.entra_login, name="entra_login"),
|
||||||
path("auth/redirect/", views.entra_callback, name="entra_callback"),
|
path("auth/redirect/", views.entra_callback, name="entra_callback"),
|
||||||
path("auth/token/", views.get_token, name="get_token"),
|
|
||||||
]
|
]
|
||||||
|
|||||||
132
epauth/views.py
@ -1,32 +1,10 @@
|
|||||||
import msal
|
import msal
|
||||||
from django.conf import settings as s
|
from django.conf import settings as s
|
||||||
from django.contrib.auth import get_user_model
|
|
||||||
from django.contrib.auth import login
|
from django.contrib.auth import login
|
||||||
from django.http import HttpResponse
|
|
||||||
from django.shortcuts import redirect
|
from django.shortcuts import redirect
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
|
||||||
from epdb.logic import UserManager, GroupManager
|
from epdb.logic import UserManager
|
||||||
from epdb.models import Group
|
|
||||||
|
|
||||||
|
|
||||||
def get_msal_app_with_cache(request):
|
|
||||||
"""
|
|
||||||
Create MSAL app with session-based token cache.
|
|
||||||
"""
|
|
||||||
cache = msal.SerializableTokenCache()
|
|
||||||
|
|
||||||
# Load cache from session if it exists
|
|
||||||
if request.session.get("msal_token_cache"):
|
|
||||||
cache.deserialize(request.session["msal_token_cache"])
|
|
||||||
|
|
||||||
msal_app = msal.ConfidentialClientApplication(
|
|
||||||
client_id=s.MS_ENTRA_CLIENT_ID,
|
|
||||||
client_credential=s.MS_ENTRA_CLIENT_SECRET,
|
|
||||||
authority=s.MS_ENTRA_AUTHORITY,
|
|
||||||
token_cache=cache,
|
|
||||||
)
|
|
||||||
|
|
||||||
return msal_app, cache
|
|
||||||
|
|
||||||
|
|
||||||
def entra_login(request):
|
def entra_login(request):
|
||||||
@ -45,7 +23,11 @@ def entra_login(request):
|
|||||||
|
|
||||||
|
|
||||||
def entra_callback(request):
|
def entra_callback(request):
|
||||||
msal_app, cache = get_msal_app_with_cache(request)
|
msal_app = msal.ConfidentialClientApplication(
|
||||||
|
client_id=s.MS_ENTRA_CLIENT_ID,
|
||||||
|
client_credential=s.MS_ENTRA_CLIENT_SECRET,
|
||||||
|
authority=s.MS_ENTRA_AUTHORITY,
|
||||||
|
)
|
||||||
|
|
||||||
flow = request.session.pop("msal_auth_flow", None)
|
flow = request.session.pop("msal_auth_flow", None)
|
||||||
if not flow:
|
if not flow:
|
||||||
@ -54,18 +36,11 @@ def entra_callback(request):
|
|||||||
# Acquire token using the flow and callback request
|
# Acquire token using the flow and callback request
|
||||||
result = msal_app.acquire_token_by_auth_code_flow(flow, request.GET)
|
result = msal_app.acquire_token_by_auth_code_flow(flow, request.GET)
|
||||||
|
|
||||||
# Save the token cache to session
|
|
||||||
if cache.has_state_changed:
|
|
||||||
request.session["msal_token_cache"] = cache.serialize()
|
|
||||||
|
|
||||||
claims = result["id_token_claims"]
|
claims = result["id_token_claims"]
|
||||||
|
|
||||||
user_name = claims.get("name")
|
user_name = claims["name"]
|
||||||
user_email = claims.get("emailaddress", claims.get("email"))
|
user_email = claims["emailaddress"]
|
||||||
user_oid = claims.get("oid")
|
user_oid = claims["oid"]
|
||||||
|
|
||||||
if not all([user_name, user_email, user_oid]):
|
|
||||||
raise ValueError("Missing required claims in ID token")
|
|
||||||
|
|
||||||
# Get implementing class
|
# Get implementing class
|
||||||
User = get_user_model()
|
User = get_user_model()
|
||||||
@ -82,89 +57,4 @@ def entra_callback(request):
|
|||||||
|
|
||||||
login(request, u)
|
login(request, u)
|
||||||
|
|
||||||
# EDIT START
|
return redirect("/") # Handle errors
|
||||||
|
|
||||||
# Ensure groups exists in eP
|
|
||||||
for id, name in s.ENTRA_SECRET_GROUPS.items():
|
|
||||||
if not Group.objects.filter(uuid=id).exists():
|
|
||||||
g = GroupManager.create_group(User.objects.get(username="admin"), name, f"Synced Entra Group {name} ",
|
|
||||||
uuid=id)
|
|
||||||
else:
|
|
||||||
g = Group.objects.get(uuid=id)
|
|
||||||
# Ensure its secret
|
|
||||||
g.secret = True
|
|
||||||
g.save()
|
|
||||||
|
|
||||||
for id, name in s.ENTRA_GROUPS.items():
|
|
||||||
if not Group.objects.filter(uuid=id).exists():
|
|
||||||
g = GroupManager.create_group(User.objects.get(username="admin"), name, f"Synced Entra Group {name} ",
|
|
||||||
uuid=id)
|
|
||||||
else:
|
|
||||||
g = Group.objects.get(uuid=id)
|
|
||||||
|
|
||||||
for group_uuid in claims.get("groups", []):
|
|
||||||
if Group.objects.filter(uuid=group_uuid).exists():
|
|
||||||
g = Group.objects.get(uuid=group_uuid)
|
|
||||||
g.user_member.add(u)
|
|
||||||
|
|
||||||
# EDIT END
|
|
||||||
|
|
||||||
return redirect(s.SERVER_URL) # Handle errors
|
|
||||||
|
|
||||||
|
|
||||||
def get_access_token_from_request(request, scopes=None):
|
|
||||||
"""
|
|
||||||
Get an access token from the request using MSAL token cache.
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Check if auth via Access Token
|
|
||||||
if request.headers.get("Authorization"):
|
|
||||||
return {"access_token": request.headers.get("Authorization").split(" ")[1]}
|
|
||||||
|
|
||||||
if scopes is None:
|
|
||||||
scopes = s.MS_ENTRA_SCOPES
|
|
||||||
|
|
||||||
# Get user from request (must be authenticated)
|
|
||||||
if not request.user.is_authenticated:
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Create MSAL app with persistent cache
|
|
||||||
msal_app, cache = get_msal_app_with_cache(request)
|
|
||||||
|
|
||||||
# Try to get accounts from cache
|
|
||||||
accounts = msal_app.get_accounts()
|
|
||||||
|
|
||||||
if not accounts:
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Find the account that matches the current user
|
|
||||||
user_account = None
|
|
||||||
for account in accounts:
|
|
||||||
if account.get("local_account_id") == str(request.user.uuid):
|
|
||||||
user_account = account
|
|
||||||
break
|
|
||||||
|
|
||||||
# If no matching account found, use the first available account
|
|
||||||
if not user_account and accounts:
|
|
||||||
user_account = accounts[0]
|
|
||||||
|
|
||||||
if not user_account:
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Try to acquire token silently from cache
|
|
||||||
result = msal_app.acquire_token_silent(scopes=scopes, account=user_account)
|
|
||||||
|
|
||||||
# Save cache changes back to session
|
|
||||||
if cache.has_state_changed:
|
|
||||||
request.session["msal_token_cache"] = cache.serialize()
|
|
||||||
|
|
||||||
if result and "access_token" in result:
|
|
||||||
return result
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def get_token(request):
|
|
||||||
token = get_access_token_from_request(request)
|
|
||||||
msg = f"{token}"
|
|
||||||
return HttpResponse(msg, content_type='text/plain')
|
|
||||||
|
|||||||
112
epdb/admin.py
@ -1,8 +1,5 @@
|
|||||||
import logging
|
|
||||||
|
|
||||||
from django.conf import settings as s
|
from django.conf import settings as s
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from django.contrib import messages
|
|
||||||
|
|
||||||
from .models import (
|
from .models import (
|
||||||
AdditionalInformation,
|
AdditionalInformation,
|
||||||
@ -32,8 +29,6 @@ from .models import (
|
|||||||
|
|
||||||
Package = s.GET_PACKAGE_MODEL()
|
Package = s.GET_PACKAGE_MODEL()
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class AdditionalInformationAdmin(admin.ModelAdmin):
|
class AdditionalInformationAdmin(admin.ModelAdmin):
|
||||||
pass
|
pass
|
||||||
@ -50,113 +45,6 @@ class UserAdmin(admin.ModelAdmin):
|
|||||||
"date_joined",
|
"date_joined",
|
||||||
]
|
]
|
||||||
|
|
||||||
actions = ["send_welcome_mail", "send_affiliation_mail"]
|
|
||||||
|
|
||||||
@admin.action(description="Send welcome mail")
|
|
||||||
def send_welcome_mail(self, request, queryset):
|
|
||||||
from django.core.mail import EmailMultiAlternatives
|
|
||||||
|
|
||||||
tpl = """Hello {username},
|
|
||||||
|
|
||||||
Your account has been successfully activated.
|
|
||||||
|
|
||||||
To log in, please visit
|
|
||||||
https://envipath.org/password_reset/
|
|
||||||
and request a new password.
|
|
||||||
|
|
||||||
If you have any questions or feedback, feel free to visit our community forum at
|
|
||||||
https://community.envipath.org/.
|
|
||||||
You do not need to register again for the forum - you can log in using your enviPath account by clicking "Log In" and then "Log in with enviPath."
|
|
||||||
|
|
||||||
Best regards,
|
|
||||||
|
|
||||||
The enviPath Team"""
|
|
||||||
|
|
||||||
users = []
|
|
||||||
|
|
||||||
for user in queryset:
|
|
||||||
if user.is_active:
|
|
||||||
logger.info(f"{user.username} already active - not sending mail again")
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
msg = EmailMultiAlternatives(
|
|
||||||
"Your enviPath Account Is Now Active",
|
|
||||||
tpl.format(username=user.username),
|
|
||||||
"admin@envipath.org",
|
|
||||||
[user.email],
|
|
||||||
bcc=["admin@envipath.org"],
|
|
||||||
)
|
|
||||||
|
|
||||||
msg.send(fail_silently=False)
|
|
||||||
|
|
||||||
user.is_active = True
|
|
||||||
user.password = "ASDF"
|
|
||||||
user.save()
|
|
||||||
|
|
||||||
users.append(user)
|
|
||||||
logger.info(f"{user.username} -> {user.email} mail sent")
|
|
||||||
except Exception as e:
|
|
||||||
logger.info(f"Error sending mail to {user.username}: {e}")
|
|
||||||
|
|
||||||
self.message_user(
|
|
||||||
request, f"Sent welcome mail to {[u.email for u in users]}", messages.SUCCESS
|
|
||||||
)
|
|
||||||
|
|
||||||
@admin.action(description="Send affiliation mail")
|
|
||||||
def send_affiliation_mail(self, request, queryset):
|
|
||||||
from django.core.mail import EmailMultiAlternatives
|
|
||||||
|
|
||||||
tpl = """Dear {username},
|
|
||||||
|
|
||||||
Thank you for your interest in enviPath!
|
|
||||||
|
|
||||||
Please note that the public enviPath system is intended for non-commercial use only.
|
|
||||||
We see that you registered using the email address {email}.
|
|
||||||
If possible, we kindly ask you to register using an official email address that reflects your affiliation (e.g., a university, NGO, or research organization).
|
|
||||||
|
|
||||||
If you would like us to update your account, simply reply to this email and let us know which address we should use.
|
|
||||||
We will then change it in our system, and you will receive a password reset email at the new address.
|
|
||||||
|
|
||||||
If you are registering with a company email address and are interested in commercial use, you are very welcome to book a meeting with us so we can discuss how we can best support you.
|
|
||||||
To book a meeting, please visit https://envipath.com/book
|
|
||||||
|
|
||||||
If changing to an affiliation email address is not possible, please contact us at registration@envipath.org
|
|
||||||
|
|
||||||
Best regards,
|
|
||||||
|
|
||||||
enviPath team"""
|
|
||||||
|
|
||||||
users = []
|
|
||||||
|
|
||||||
for user in queryset:
|
|
||||||
if user.is_active or user.contacted:
|
|
||||||
logger.info(
|
|
||||||
f"{user.username} already active or already contacted - not sending mail again"
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
msg = EmailMultiAlternatives(
|
|
||||||
"Regarding your enviPath registration",
|
|
||||||
tpl.format(username=user.username, email=user.email),
|
|
||||||
"admin@envipath.org",
|
|
||||||
[user.email],
|
|
||||||
bcc=["admin@envipath.org"],
|
|
||||||
)
|
|
||||||
|
|
||||||
msg.send(fail_silently=False)
|
|
||||||
|
|
||||||
user.contacted = True
|
|
||||||
user.save()
|
|
||||||
|
|
||||||
users.append(user)
|
|
||||||
logger.info(f"{user.username} -> {user.email} affiliation mail sent")
|
|
||||||
except Exception as e:
|
|
||||||
logger.info(f"Error sending mail to {user.username}: {e}")
|
|
||||||
|
|
||||||
self.message_user(
|
|
||||||
request, f"Sent affiliation mail to {[u.email for u in users]}", messages.SUCCESS
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class UserPackagePermissionAdmin(admin.ModelAdmin):
|
class UserPackagePermissionAdmin(admin.ModelAdmin):
|
||||||
pass
|
pass
|
||||||
|
|||||||
@ -1,10 +0,0 @@
|
|||||||
class InvalidSMILESException(Exception):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class InvalidMolfileException(Exception):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class PackageImportException(Exception):
|
|
||||||
pass
|
|
||||||
@ -1,17 +1,13 @@
|
|||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
import jwt
|
|
||||||
import nh3
|
import nh3
|
||||||
import requests
|
|
||||||
from django.conf import settings as s
|
from django.conf import settings as s
|
||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
from django.core.cache import cache
|
|
||||||
from django.http import HttpResponse, JsonResponse
|
from django.http import HttpResponse, JsonResponse
|
||||||
from django.shortcuts import redirect
|
from django.shortcuts import redirect
|
||||||
from jwt import InvalidIssuerError
|
|
||||||
from ninja import Field, Form, Query, Router, Schema
|
from ninja import Field, Form, Query, Router, Schema
|
||||||
from ninja.security import HttpBearer
|
from ninja.security import SessionAuth
|
||||||
|
|
||||||
from utilities.chem import FormatConverter
|
from utilities.chem import FormatConverter
|
||||||
from utilities.misc import PackageExporter
|
from utilities.misc import PackageExporter
|
||||||
@ -50,26 +46,6 @@ from .models import (
|
|||||||
Package = s.GET_PACKAGE_MODEL()
|
Package = s.GET_PACKAGE_MODEL()
|
||||||
|
|
||||||
|
|
||||||
def get_cached_jwks(tenant_id: str, force=False) -> Dict:
|
|
||||||
"""Get JWKS using Django cache"""
|
|
||||||
cache_key = f"jwks_{tenant_id}"
|
|
||||||
|
|
||||||
jwks = cache.get(cache_key)
|
|
||||||
|
|
||||||
if jwks is None or force:
|
|
||||||
# Cache miss, fetch new keys
|
|
||||||
jwks_uri = f"https://login.microsoftonline.com/{tenant_id}/discovery/v2.0/keys"
|
|
||||||
response = requests.get(jwks_uri)
|
|
||||||
response.raise_for_status()
|
|
||||||
|
|
||||||
jwks = response.json()
|
|
||||||
|
|
||||||
# Cache for 1 hour (3600 seconds)
|
|
||||||
cache.set(cache_key, jwks, 3600)
|
|
||||||
|
|
||||||
return jwks
|
|
||||||
|
|
||||||
|
|
||||||
def get_package_for_write(user, package_uuid):
|
def get_package_for_write(user, package_uuid):
|
||||||
p = PackageManager.get_package_by_id(user, package_uuid)
|
p = PackageManager.get_package_by_id(user, package_uuid)
|
||||||
if not PackageManager.writable(user, p):
|
if not PackageManager.writable(user, p):
|
||||||
@ -83,52 +59,7 @@ def _anonymous_or_real(request):
|
|||||||
return get_user_model().objects.get(username="anonymous")
|
return get_user_model().objects.get(username="anonymous")
|
||||||
|
|
||||||
|
|
||||||
def validate_token(token: str) -> dict:
|
router = Router(auth=SessionAuth(csrf=False))
|
||||||
TENANT_ID = s.MS_ENTRA_TENANT_ID
|
|
||||||
CLIENT_ID = s.MS_ENTRA_CLIENT_ID
|
|
||||||
|
|
||||||
jwks = get_cached_jwks(TENANT_ID)
|
|
||||||
|
|
||||||
header = jwt.get_unverified_header(token)
|
|
||||||
|
|
||||||
public_key = jwt.algorithms.RSAAlgorithm.from_jwk(
|
|
||||||
next(k for k in jwks["keys"] if k["kid"] == header["kid"])
|
|
||||||
)
|
|
||||||
|
|
||||||
# Handle V1 and V2 tokens
|
|
||||||
try:
|
|
||||||
claims = jwt.decode(
|
|
||||||
token,
|
|
||||||
public_key,
|
|
||||||
algorithms=["RS256"],
|
|
||||||
audience=[CLIENT_ID, f"api://{CLIENT_ID}"],
|
|
||||||
issuer=[
|
|
||||||
f"https://sts.windows.net/{TENANT_ID}/",
|
|
||||||
f"https://login.microsoftonline.com/{TENANT_ID}/v2.0"
|
|
||||||
]
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
raise ValueError(f"Token verification failed! - {e}")
|
|
||||||
|
|
||||||
return claims
|
|
||||||
|
|
||||||
|
|
||||||
class MSBearerTokenAuth(HttpBearer):
|
|
||||||
|
|
||||||
def authenticate(self, request, token):
|
|
||||||
if token is None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
claims = validate_token(token)
|
|
||||||
|
|
||||||
if not User.objects.filter(uuid=claims['oid']).exists():
|
|
||||||
return None
|
|
||||||
|
|
||||||
request.user = User.objects.get(uuid=claims['oid'])
|
|
||||||
return request.user
|
|
||||||
|
|
||||||
|
|
||||||
router = Router(auth=MSBearerTokenAuth())
|
|
||||||
|
|
||||||
|
|
||||||
class Error(Schema):
|
class Error(Schema):
|
||||||
@ -222,6 +153,21 @@ class SimpleModel(SimpleObject):
|
|||||||
identifier: str = "relative-reasoning"
|
identifier: str = "relative-reasoning"
|
||||||
|
|
||||||
|
|
||||||
|
################
|
||||||
|
# Login/Logout #
|
||||||
|
################
|
||||||
|
@router.post("/", response={200: SimpleUser, 403: Error}, auth=None)
|
||||||
|
def login(request, loginusername: Form[str], loginpassword: Form[str]):
|
||||||
|
from django.contrib.auth import authenticate, login
|
||||||
|
|
||||||
|
email = User.objects.get(username=loginusername).email
|
||||||
|
user = authenticate(username=email, password=loginpassword)
|
||||||
|
if user:
|
||||||
|
login(request, user)
|
||||||
|
return user
|
||||||
|
else:
|
||||||
|
return 403, {"message": "Invalid username and/or password"}
|
||||||
|
|
||||||
|
|
||||||
########
|
########
|
||||||
# User #
|
# User #
|
||||||
@ -440,50 +386,23 @@ class PackageSchema(Schema):
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def resolve_readers(obj: Package):
|
def resolve_readers(obj: Package):
|
||||||
readers = []
|
users = User.objects.filter(
|
||||||
|
id__in=UserPackagePermission.objects.filter(
|
||||||
|
package=obj, permission=UserPackagePermission.READ[0]
|
||||||
|
).values_list("user", flat=True)
|
||||||
|
).distinct()
|
||||||
|
|
||||||
user_ids = UserPackagePermission.objects.filter(package=obj).values_list("user", flat=True)
|
return [{u.id: u.get_name()} for u in users]
|
||||||
|
|
||||||
users = User.objects.filter(id__in=user_ids).distinct()
|
|
||||||
|
|
||||||
for u in users:
|
|
||||||
readers.append({"id": str(u.url), "identifier": "user", "name": u.get_name()})
|
|
||||||
|
|
||||||
group_ids = GroupPackagePermission.objects.filter(package=obj).values_list(
|
|
||||||
"group", flat=True
|
|
||||||
)
|
|
||||||
|
|
||||||
groups = Group.objects.filter(id__in=group_ids).distinct()
|
|
||||||
|
|
||||||
for g in groups:
|
|
||||||
readers.append({"id": str(g.url), "identifier": "group", "name": g.get_name()})
|
|
||||||
|
|
||||||
return readers
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def resolve_writers(obj: Package):
|
def resolve_writers(obj: Package):
|
||||||
writers = []
|
users = User.objects.filter(
|
||||||
|
id__in=UserPackagePermission.objects.filter(
|
||||||
user_ids = UserPackagePermission.objects.filter(
|
package=obj, permission=UserPackagePermission.WRITE[0]
|
||||||
package=obj,
|
|
||||||
permission__in=[UserPackagePermission.WRITE[0], UserPackagePermission.ALL[0]],
|
|
||||||
).values_list("user", flat=True)
|
).values_list("user", flat=True)
|
||||||
|
).distinct()
|
||||||
|
|
||||||
users = User.objects.filter(id__in=user_ids).distinct()
|
return [{u.id: u.get_name()} for u in users]
|
||||||
|
|
||||||
for u in users:
|
|
||||||
writers.append({"id": str(u.url), "identifier": "user", "name": u.get_name()})
|
|
||||||
|
|
||||||
group_ids = GroupPackagePermission.objects.filter(
|
|
||||||
package=obj, permission=[UserPackagePermission.WRITE[0], UserPackagePermission.ALL[0]]
|
|
||||||
).values_list("group", flat=True)
|
|
||||||
|
|
||||||
groups = Group.objects.filter(id__in=group_ids).distinct()
|
|
||||||
|
|
||||||
for g in groups:
|
|
||||||
writers.append({"id": str(g.url), "identifier": "group", "name": g.get_name()})
|
|
||||||
|
|
||||||
return writers
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def resolve_review_comment(obj):
|
def resolve_review_comment(obj):
|
||||||
@ -634,14 +553,9 @@ class CompoundSchema(Schema):
|
|||||||
reviewStatus: str = Field(False, alias="review_status")
|
reviewStatus: str = Field(False, alias="review_status")
|
||||||
scenarios: List["SimpleScenario"] = Field([], alias="scenarios")
|
scenarios: List["SimpleScenario"] = Field([], alias="scenarios")
|
||||||
structures: List["CompoundStructureSchema"] = []
|
structures: List["CompoundStructureSchema"] = []
|
||||||
pesLink: str | None = Field(None, alias="pes_link")
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def resolve_pes_link(obj: Compound):
|
def resolve_review_status(obj: CompoundStructure):
|
||||||
return getattr(obj.default_structure, "pes_link", None)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def resolve_review_status(obj: Compound):
|
|
||||||
return "reviewed" if obj.package.reviewed else "unreviewed"
|
return "reviewed" if obj.package.reviewed else "unreviewed"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@ -715,7 +629,6 @@ class CompoundStructureSchema(Schema):
|
|||||||
reviewStatus: str = Field(None, alias="review_status")
|
reviewStatus: str = Field(None, alias="review_status")
|
||||||
scenarios: List["SimpleScenario"] = Field([], alias="scenarios")
|
scenarios: List["SimpleScenario"] = Field([], alias="scenarios")
|
||||||
smiles: str = Field(None, alias="smiles")
|
smiles: str = Field(None, alias="smiles")
|
||||||
pesLink: str | None = Field(None, alias="pes_link")
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def resolve_review_status(obj: CompoundStructure):
|
def resolve_review_status(obj: CompoundStructure):
|
||||||
@ -851,11 +764,9 @@ def get_package_compound_structure(request, package_uuid, compound_uuid, structu
|
|||||||
|
|
||||||
class CreateCompound(Schema):
|
class CreateCompound(Schema):
|
||||||
compoundSmiles: str
|
compoundSmiles: str
|
||||||
compoundMolFile: str | None = None
|
|
||||||
compoundName: str | None = None
|
compoundName: str | None = None
|
||||||
compoundDescription: str | None = None
|
compoundDescription: str | None = None
|
||||||
inchi: str | None = None
|
inchi: str | None = None
|
||||||
pesLink: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/package/{uuid:package_uuid}/compound")
|
@router.post("/package/{uuid:package_uuid}/compound")
|
||||||
@ -867,36 +778,8 @@ def create_package_compound(
|
|||||||
try:
|
try:
|
||||||
p = get_package_for_write(request.user, package_uuid)
|
p = get_package_for_write(request.user, package_uuid)
|
||||||
# inchi is not used atm
|
# inchi is not used atm
|
||||||
|
|
||||||
if c.pesLink is not None:
|
|
||||||
from bayer.views import fetch_pes
|
|
||||||
from bayer.models import PESCompound
|
|
||||||
|
|
||||||
try:
|
|
||||||
pes_data = fetch_pes(request, c.pesLink)
|
|
||||||
except ValueError as e:
|
|
||||||
return 400, {"message": f"Could not fetch PES data for {c.pesLink}"}
|
|
||||||
|
|
||||||
classification = pes_data.get("classificationLevel", "")
|
|
||||||
if "secret" == classification.lower():
|
|
||||||
|
|
||||||
if p.classification_level != Package.Classification.SECRET:
|
|
||||||
return 400, {"Cannot create PESs for non-secret packages."}
|
|
||||||
|
|
||||||
data_pools = pes_data.get("dataPools")
|
|
||||||
if data_pools:
|
|
||||||
if s.DATA_POOL_MAPPING[p.data_pool.name] not in data_pools:
|
|
||||||
return 400, { "messsage": f"PES data pool {s.DATA_POOL_MAPPING[p.data_pool.name]} not found in PES data"}
|
|
||||||
|
|
||||||
c = PESCompound.create(p, pes_data, c.compoundName, c.compoundDescription)
|
|
||||||
else:
|
|
||||||
c = Compound.create(
|
c = Compound.create(
|
||||||
p,
|
p, c.compoundSmiles, c.compoundName, c.compoundDescription, inchi=c.inchi
|
||||||
c.compoundSmiles,
|
|
||||||
molfile=c.compoundMolFile,
|
|
||||||
name=c.compoundName,
|
|
||||||
description=c.compoundDescription,
|
|
||||||
inchi=c.inchi
|
|
||||||
)
|
)
|
||||||
return redirect(c.url)
|
return redirect(c.url)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
@ -916,27 +799,6 @@ def delete_compound(request, package_uuid, compound_uuid):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class CreateCompoundStructure(Schema):
|
|
||||||
smiles: str
|
|
||||||
name: str | None = None
|
|
||||||
description: str | None = None
|
|
||||||
inchi: str | None = None
|
|
||||||
molfile: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/package/{uuid:package_uuid}/compound/{uuid:compound_uuid}/structure")
|
|
||||||
def create_package_compound_structure(
|
|
||||||
request, package_uuid, compound_uuid, structure: Form[CreateCompoundStructure]
|
|
||||||
):
|
|
||||||
try:
|
|
||||||
p = get_package_for_write(request.user, package_uuid)
|
|
||||||
c = Compound.objects.get(package=p, uuid=compound_uuid)
|
|
||||||
cs = CompoundStructure.create(c, structure.smiles, structure.name, structure.description)
|
|
||||||
return redirect(cs.url)
|
|
||||||
except ValueError as e:
|
|
||||||
return 400, {"message": str(e)}
|
|
||||||
|
|
||||||
|
|
||||||
@router.delete(
|
@router.delete(
|
||||||
"/package/{uuid:package_uuid}/compound/{uuid:compound_uuid}/structure/{uuid:structure_uuid}"
|
"/package/{uuid:package_uuid}/compound/{uuid:compound_uuid}/structure/{uuid:structure_uuid}"
|
||||||
)
|
)
|
||||||
@ -1463,7 +1325,6 @@ class ScenarioSchema(Schema):
|
|||||||
aliases: List[str] = Field([], alias="aliases")
|
aliases: List[str] = Field([], alias="aliases")
|
||||||
collection: Dict["str", List[Dict[str, Any]]] = Field([], alias="collection")
|
collection: Dict["str", List[Dict[str, Any]]] = Field([], alias="collection")
|
||||||
collectionID: Optional[str] = None
|
collectionID: Optional[str] = None
|
||||||
date: str = Field(None, alias="scenario_date")
|
|
||||||
description: str = Field(None, alias="description")
|
description: str = Field(None, alias="description")
|
||||||
id: str = Field(None, alias="url")
|
id: str = Field(None, alias="url")
|
||||||
identifier: str = "scenario"
|
identifier: str = "scenario"
|
||||||
@ -1607,7 +1468,6 @@ def create_package_additional_information(request, package_uuid):
|
|||||||
scen = request.POST.get("scenario")
|
scen = request.POST.get("scenario")
|
||||||
scenario = Scenario.objects.get(package=p, url=scen)
|
scenario = Scenario.objects.get(package=p, url=scen)
|
||||||
|
|
||||||
if request.POST.get("adInfoTypes[]"):
|
|
||||||
url_parser = EPDBURLParser(request.POST.get("attach_obj"))
|
url_parser = EPDBURLParser(request.POST.get("attach_obj"))
|
||||||
attach_obj = url_parser.get_object()
|
attach_obj = url_parser.get_object()
|
||||||
|
|
||||||
@ -1631,33 +1491,6 @@ def create_package_additional_information(request, package_uuid):
|
|||||||
content_object=attach_obj,
|
content_object=attach_obj,
|
||||||
)
|
)
|
||||||
|
|
||||||
elif request.POST.get("ais"):
|
|
||||||
import json
|
|
||||||
|
|
||||||
parsed_ais = json.loads(request.POST.get("ais"))
|
|
||||||
|
|
||||||
for ai_type, ais in parsed_ais.items():
|
|
||||||
for ai in ais:
|
|
||||||
attach_obj = None
|
|
||||||
if ai.get("related"):
|
|
||||||
url_parser = EPDBURLParser(ai.get("related").get("url"))
|
|
||||||
attach_obj = url_parser.get_object()
|
|
||||||
|
|
||||||
if not hasattr(attach_obj, "additional_information"):
|
|
||||||
raise ValueError("Can't attach additional information to this object!")
|
|
||||||
|
|
||||||
if not attach_obj.url.startswith(p.url):
|
|
||||||
raise ValueError(
|
|
||||||
"Additional Information can only be set to objects stored in the same package!"
|
|
||||||
)
|
|
||||||
|
|
||||||
AdditionalInformation.create(
|
|
||||||
p,
|
|
||||||
AdditionalInformation.from_dict(ai_type, ai),
|
|
||||||
scenario=scenario,
|
|
||||||
content_object=attach_obj,
|
|
||||||
)
|
|
||||||
|
|
||||||
# TODO implement additional information endpoint ?
|
# TODO implement additional information endpoint ?
|
||||||
return redirect(f"{scenario.url}")
|
return redirect(f"{scenario.url}")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
@ -1700,15 +1533,13 @@ class PathwayNode(Schema):
|
|||||||
dt50s: List[Dict[str, str]] = Field([], alias="dt50s")
|
dt50s: List[Dict[str, str]] = Field([], alias="dt50s")
|
||||||
engineeredIntermediate: bool = Field(None, alias="engineered_intermediate")
|
engineeredIntermediate: bool = Field(None, alias="engineered_intermediate")
|
||||||
id: str = Field(None, alias="url")
|
id: str = Field(None, alias="url")
|
||||||
idcomp: str = Field(None, alias="node_label_id")
|
idcomp: str = Field(None, alias="default_node_label.url")
|
||||||
idreact: str = Field(None, alias="node_label_id")
|
idreact: str = Field(None, alias="default_node_label.url")
|
||||||
image: str = Field(None, alias="image")
|
image: str = Field(None, alias="image")
|
||||||
imageSize: int = Field(None, alias="image_size")
|
imageSize: int = Field(None, alias="image_size")
|
||||||
name: str = Field(None, alias="name")
|
name: str = Field(None, alias="name")
|
||||||
proposed: List[Dict[str, str]] = []
|
proposed: List[Dict[str, str]] = Field([], alias="proposed_intermediate")
|
||||||
smiles: str = Field(None, alias="smiles")
|
smiles: str = Field(None, alias="default_node_label.smiles")
|
||||||
pseudo: bool = Field(False, alias="pseudo")
|
|
||||||
pesLink: str | None = Field(None, alias="pes_link")
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def resolve_atom_count(obj: Node):
|
def resolve_atom_count(obj: Node):
|
||||||
@ -1721,10 +1552,24 @@ class PathwayNode(Schema):
|
|||||||
# TODO
|
# TODO
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def resolve_engineered_intermediate(obj: Node):
|
||||||
|
# TODO
|
||||||
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def resolve_image(obj: Node):
|
||||||
|
return f"{obj.default_node_label.url}?image=svg"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def resolve_image_size(obj: Node):
|
def resolve_image_size(obj: Node):
|
||||||
return 400
|
return 400
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def resolve_proposed_intermediate(obj: Node):
|
||||||
|
# TODO
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
class PathwaySchema(Schema):
|
class PathwaySchema(Schema):
|
||||||
aliases: List[str] = Field([], alias="aliases")
|
aliases: List[str] = Field([], alias="aliases")
|
||||||
@ -1848,29 +1693,6 @@ def create_package_pathway(
|
|||||||
return 403, {"message": str(e)}
|
return 403, {"message": str(e)}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/package/{uuid:package_uuid}/pathway/{uuid:pathway_uuid}")
|
|
||||||
def update_pathway(request, package_uuid, pathway_uuid):
|
|
||||||
try:
|
|
||||||
p = get_package_for_write(request.user, package_uuid)
|
|
||||||
|
|
||||||
if request.POST.get("scenario"):
|
|
||||||
pw = Pathway.objects.get(package=p, uuid=pathway_uuid)
|
|
||||||
scen = Scenario.objects.get(package=p, url=request.POST.get("scenario"))
|
|
||||||
|
|
||||||
pw.scenarios.add(scen)
|
|
||||||
pw.save()
|
|
||||||
|
|
||||||
return redirect(f"{pw.url}")
|
|
||||||
|
|
||||||
else:
|
|
||||||
return 400, {"message": "No scenario specified!"}
|
|
||||||
|
|
||||||
except ValueError:
|
|
||||||
return 403, {
|
|
||||||
"message": f"Deleting Pathway with id {pathway_uuid} failed due to insufficient rights!"
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/package/{uuid:package_uuid}/pathway/{uuid:pathway_uuid}")
|
@router.delete("/package/{uuid:package_uuid}/pathway/{uuid:pathway_uuid}")
|
||||||
def delete_pathway(request, package_uuid, pathway_uuid):
|
def delete_pathway(request, package_uuid, pathway_uuid):
|
||||||
try:
|
try:
|
||||||
@ -1976,78 +1798,28 @@ def get_package_pathway_node(request, package_uuid, pathway_uuid, node_uuid):
|
|||||||
|
|
||||||
class CreateNode(Schema):
|
class CreateNode(Schema):
|
||||||
nodeAsSmiles: str
|
nodeAsSmiles: str
|
||||||
nodeAsMolFile: str | None = None
|
|
||||||
nodeName: str | None = None
|
nodeName: str | None = None
|
||||||
nodeReason: str | None = None
|
nodeReason: str | None = None
|
||||||
nodeDepth: str | None = None
|
nodeDepth: str | None = None
|
||||||
pesLink: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
"/package/{uuid:package_uuid}/pathway/{uuid:pathway_uuid}/node",
|
"/package/{uuid:package_uuid}/pathway/{uuid:pathway_uuid}/node",
|
||||||
response={200: str | Any, 400: Error, 403: Error},
|
response={200: str | Any, 403: Error},
|
||||||
)
|
)
|
||||||
def add_pathway_node(request, package_uuid, pathway_uuid, n: Form[CreateNode]):
|
def add_pathway_node(request, package_uuid, pathway_uuid, n: Form[CreateNode]):
|
||||||
try:
|
try:
|
||||||
p = get_package_for_write(request.user, package_uuid)
|
p = get_package_for_write(request.user, package_uuid)
|
||||||
pw = Pathway.objects.get(package=p, uuid=pathway_uuid)
|
pw = Pathway.objects.get(package=p, uuid=pathway_uuid)
|
||||||
|
|
||||||
# TODO Code Dup from bayer.views
|
|
||||||
|
|
||||||
if n.pesLink:
|
|
||||||
from bayer.views import fetch_pes
|
|
||||||
from bayer.models import PESCompound
|
|
||||||
|
|
||||||
try:
|
|
||||||
pes_data = fetch_pes(request, n.pesLink)
|
|
||||||
except ValueError as e:
|
|
||||||
return 400, {"message": f"Could not fetch PES data for {n.pesLink}"}
|
|
||||||
|
|
||||||
classification = pes_data.get("classificationLevel", "")
|
|
||||||
if "secret" == classification.lower():
|
|
||||||
|
|
||||||
if p.classification_level != Package.Classification.SECRET:
|
|
||||||
return 400, "Cannot create PESs for non-secret packages."
|
|
||||||
|
|
||||||
data_pools = pes_data.get("dataPools")
|
|
||||||
if data_pools:
|
|
||||||
if s.DATA_POOL_MAPPING[p.data_pool.name] not in data_pools:
|
|
||||||
return 400, {
|
|
||||||
"messsage": f"PES data pool {s.DATA_POOL_MAPPING[p.data_pool.name]} not found in PES data"
|
|
||||||
}
|
|
||||||
|
|
||||||
c = PESCompound.create(p, pes_data, n.nodeName, n.nodeReason)
|
|
||||||
|
|
||||||
node_qs = Node.objects.filter(pathway=pw, default_node_label=c.default_structure)
|
|
||||||
if node_qs.exists():
|
|
||||||
return redirect(pw.url)
|
|
||||||
|
|
||||||
node = Node()
|
|
||||||
node.stereo_removed = False
|
|
||||||
node.pathway = pw
|
|
||||||
node.depth = 0
|
|
||||||
|
|
||||||
node.default_node_label = c.default_structure
|
|
||||||
node.save()
|
|
||||||
|
|
||||||
node.node_labels.add(c.default_structure)
|
|
||||||
node.save()
|
|
||||||
else:
|
|
||||||
if n.nodeDepth is not None and n.nodeDepth.strip() != "":
|
if n.nodeDepth is not None and n.nodeDepth.strip() != "":
|
||||||
node_depth = int(n.nodeDepth)
|
node_depth = int(n.nodeDepth)
|
||||||
else:
|
else:
|
||||||
node_depth = -1
|
node_depth = -1
|
||||||
|
|
||||||
node = Node.create(
|
n = Node.create(pw, n.nodeAsSmiles, node_depth, n.nodeName, n.nodeReason)
|
||||||
pw,
|
|
||||||
n.nodeAsSmiles,
|
|
||||||
node_depth,
|
|
||||||
molfile=n.nodeAsMolFile,
|
|
||||||
name=n.nodeName,
|
|
||||||
description=n.nodeReason,
|
|
||||||
)
|
|
||||||
|
|
||||||
return redirect(node.url)
|
return redirect(n.url)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return 403, {"message": "Adding node failed!"}
|
return 403, {"message": "Adding node failed!"}
|
||||||
|
|
||||||
@ -2157,16 +1929,13 @@ def add_pathway_edge(request, package_uuid, pathway_uuid, e: Form[CreateEdge]):
|
|||||||
educts = []
|
educts = []
|
||||||
products = []
|
products = []
|
||||||
|
|
||||||
subclasses = CompoundStructure.__subclasses__()
|
|
||||||
|
|
||||||
if e.edgeAsSmirks:
|
if e.edgeAsSmirks:
|
||||||
for ed in e.edgeAsSmirks.split(">>")[0].split("\\."):
|
for ed in e.edgeAsSmirks.split(">>")[0].split("\\."):
|
||||||
stand_ed = FormatConverter.standardize(ed, remove_stereo=True)
|
stand_ed = FormatConverter.standardize(ed, remove_stereo=True)
|
||||||
educts.append(
|
educts.append(
|
||||||
Node.objects.get(
|
Node.objects.get(
|
||||||
pathway=pw,
|
pathway=pw,
|
||||||
default_node_label=CompoundStructure.objects.not_instance_of(*subclasses).
|
default_node_label=CompoundStructure.objects.get(
|
||||||
get(
|
|
||||||
compound__package=p, smiles=stand_ed
|
compound__package=p, smiles=stand_ed
|
||||||
).compound.default_structure,
|
).compound.default_structure,
|
||||||
)
|
)
|
||||||
@ -2177,8 +1946,7 @@ def add_pathway_edge(request, package_uuid, pathway_uuid, e: Form[CreateEdge]):
|
|||||||
products.append(
|
products.append(
|
||||||
Node.objects.get(
|
Node.objects.get(
|
||||||
pathway=pw,
|
pathway=pw,
|
||||||
default_node_label=CompoundStructure.objects.not_instance_of(*subclasses).
|
default_node_label=CompoundStructure.objects.get(
|
||||||
get(
|
|
||||||
compound__package=p, smiles=stand_pr
|
compound__package=p, smiles=stand_pr
|
||||||
).compound.default_structure,
|
).compound.default_structure,
|
||||||
)
|
)
|
||||||
@ -2190,10 +1958,6 @@ def add_pathway_edge(request, package_uuid, pathway_uuid, e: Form[CreateEdge]):
|
|||||||
for pr in e.products.split(","):
|
for pr in e.products.split(","):
|
||||||
products.append(Node.objects.get(pathway=pw, url=pr.strip()))
|
products.append(Node.objects.get(pathway=pw, url=pr.strip()))
|
||||||
|
|
||||||
multi_step = False
|
|
||||||
if e.multistep and e.multistep.strip() == "true":
|
|
||||||
multi_step = True
|
|
||||||
|
|
||||||
new_e = Edge.create(
|
new_e = Edge.create(
|
||||||
pathway=pw,
|
pathway=pw,
|
||||||
start_nodes=educts,
|
start_nodes=educts,
|
||||||
@ -2201,15 +1965,11 @@ def add_pathway_edge(request, package_uuid, pathway_uuid, e: Form[CreateEdge]):
|
|||||||
rule=None,
|
rule=None,
|
||||||
name=None,
|
name=None,
|
||||||
description=e.edgeReason,
|
description=e.edgeReason,
|
||||||
multi_step=multi_step,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Update depths as sideeffect of above operation
|
|
||||||
pw.update_depths()
|
|
||||||
|
|
||||||
return redirect(new_e.url)
|
return redirect(new_e.url)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return 403, {"message": "Adding Edge failed!"}
|
return 403, {"message": "Adding node failed!"}
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/package/{uuid:package_uuid}/pathway/{uuid:pathway_uuid}/edge/{uuid:edge_uuid}")
|
@router.delete("/package/{uuid:package_uuid}/pathway/{uuid:pathway_uuid}/edge/{uuid:edge_uuid}")
|
||||||
@ -2400,26 +2160,3 @@ def get_setting(request, setting_uuid):
|
|||||||
return 403, {
|
return 403, {
|
||||||
"message": f"Getting Setting with id {setting_uuid} failed due to insufficient rights!"
|
"message": f"Getting Setting with id {setting_uuid} failed due to insufficient rights!"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
########
|
|
||||||
# Util #
|
|
||||||
########
|
|
||||||
class NonPersistent(Schema):
|
|
||||||
smiles: str
|
|
||||||
setting_url: str = Field(..., alias="settingUri")
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/util", response={200: Any, 403: Error})
|
|
||||||
def predict(request, np: Form[NonPersistent]):
|
|
||||||
try:
|
|
||||||
from epdb.logic import SPathway
|
|
||||||
|
|
||||||
setting = SettingManager.get_setting_by_url(request.user, np.setting_url)
|
|
||||||
spw = SPathway(prediction_setting=setting, root_nodes=[np.smiles])
|
|
||||||
spw.predict()
|
|
||||||
return spw.to_json()
|
|
||||||
except ValueError:
|
|
||||||
return 403, {
|
|
||||||
"message": f"Getting Setting with id {np.setting_url} failed due to insufficient rights!"
|
|
||||||
}
|
|
||||||
|
|||||||
194
epdb/logic.py
@ -7,7 +7,6 @@ import nh3
|
|||||||
from django.conf import settings as s
|
from django.conf import settings as s
|
||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
from django.db.models import QuerySet
|
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|
||||||
from epdb.models import (
|
from epdb.models import (
|
||||||
@ -265,12 +264,8 @@ class GroupManager(object):
|
|||||||
return bool(re.findall(GroupManager.group_pattern, url))
|
return bool(re.findall(GroupManager.group_pattern, url))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def create_group(current_user, name, description, *args, **kwargs):
|
def create_group(current_user, name, description):
|
||||||
g = Group()
|
g = Group()
|
||||||
|
|
||||||
if "uuid" in kwargs:
|
|
||||||
g.uuid = kwargs["uuid"]
|
|
||||||
|
|
||||||
# Clean for potential XSS
|
# Clean for potential XSS
|
||||||
g.name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
g.name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
||||||
g.description = nh3.clean(description, tags=s.ALLOWED_HTML_TAGS).strip()
|
g.description = nh3.clean(description, tags=s.ALLOWED_HTML_TAGS).strip()
|
||||||
@ -346,17 +341,52 @@ class PackageManager(object):
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def readable(user, package):
|
def readable(user, package):
|
||||||
return (
|
if (
|
||||||
PackageManager.has_package_permission(user, package, "read") | package.reviewed is True
|
UserPackagePermission.objects.filter(package=package, user=user).exists()
|
||||||
|
or GroupPackagePermission.objects.filter(
|
||||||
|
package=package, group__in=GroupManager.get_groups(user)
|
||||||
)
|
)
|
||||||
|
or package.reviewed is True
|
||||||
|
or user.is_superuser
|
||||||
|
):
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def writable(user, package):
|
def writable(user, package):
|
||||||
return PackageManager.has_package_permission(user, package, "write")
|
if (
|
||||||
|
UserPackagePermission.objects.filter(
|
||||||
|
package=package, user=user, permission=Permission.WRITE[0]
|
||||||
|
).exists()
|
||||||
|
or GroupPackagePermission.objects.filter(
|
||||||
|
package=package,
|
||||||
|
group__in=GroupManager.get_groups(user),
|
||||||
|
permission=Permission.WRITE[0],
|
||||||
|
).exists()
|
||||||
|
or UserPackagePermission.objects.filter(
|
||||||
|
package=package, user=user, permission=Permission.ALL[0]
|
||||||
|
).exists()
|
||||||
|
or user.is_superuser
|
||||||
|
):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def administrable(user, package):
|
def administrable(user, package):
|
||||||
return PackageManager.has_package_permission(user, package, "all")
|
if (
|
||||||
|
UserPackagePermission.objects.filter(
|
||||||
|
package=package, user=user, permission=Permission.ALL[0]
|
||||||
|
).exists()
|
||||||
|
or GroupPackagePermission.objects.filter(
|
||||||
|
package=package,
|
||||||
|
group__in=GroupManager.get_groups(user),
|
||||||
|
permission=Permission.ALL[0],
|
||||||
|
).exists()
|
||||||
|
or user.is_superuser
|
||||||
|
):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def has_package_permission(user: "User", package: Union[str, UUID, "Package"], permission: str):
|
def has_package_permission(user: "User", package: Union[str, UUID, "Package"], permission: str):
|
||||||
@ -365,14 +395,6 @@ class PackageManager(object):
|
|||||||
|
|
||||||
groups = GroupManager.get_groups(user)
|
groups = GroupManager.get_groups(user)
|
||||||
|
|
||||||
# EDIT START
|
|
||||||
|
|
||||||
if package.classification_level == Package.Classification.SECRET:
|
|
||||||
if package.data_pool not in groups:
|
|
||||||
return False
|
|
||||||
|
|
||||||
# EDIT END
|
|
||||||
|
|
||||||
perms = {"all": ["all"], "write": ["all", "write"], "read": ["all", "write", "read"]}
|
perms = {"all": ["all"], "write": ["all", "write"], "read": ["all", "write", "read"]}
|
||||||
|
|
||||||
valid_perms = perms.get(permission)
|
valid_perms = perms.get(permission)
|
||||||
@ -415,7 +437,6 @@ class PackageManager(object):
|
|||||||
try:
|
try:
|
||||||
p = Package.objects.get(uuid=package_id)
|
p = Package.objects.get(uuid=package_id)
|
||||||
if PackageManager.readable(user, p):
|
if PackageManager.readable(user, p):
|
||||||
p = PackageManager.check_package_classification(user, p)
|
|
||||||
return p
|
return p
|
||||||
else:
|
else:
|
||||||
# FIXME: use custom exception to be translatable to 403 in API
|
# FIXME: use custom exception to be translatable to 403 in API
|
||||||
@ -425,37 +446,6 @@ class PackageManager(object):
|
|||||||
except Package.DoesNotExist:
|
except Package.DoesNotExist:
|
||||||
raise ValueError("Package with ID {} does not exist!".format(package_id))
|
raise ValueError("Package with ID {} does not exist!".format(package_id))
|
||||||
|
|
||||||
# EDIT START
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def check_package_classification(user, pack: Package):
|
|
||||||
if pack.classification_level == Package.Classification.SECRET:
|
|
||||||
if pack.data_pool.user_member.filter(id=user.id).exists():
|
|
||||||
return pack
|
|
||||||
|
|
||||||
raise ValueError("Package is secret and not accessible to user!")
|
|
||||||
|
|
||||||
else:
|
|
||||||
return pack
|
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def check_package_classifications(user, package_qs: QuerySet[Package]):
|
|
||||||
non_secret = package_qs.exclude(classification_level=Package.Classification.SECRET)
|
|
||||||
secret = package_qs.filter(classification_level=Package.Classification.SECRET)
|
|
||||||
|
|
||||||
# TODO we should be able to do via the db
|
|
||||||
accessible_secret = []
|
|
||||||
|
|
||||||
for s_package in secret:
|
|
||||||
if s_package.data_pool.user_member.filter(id=user.id).exists():
|
|
||||||
accessible_secret.append(s_package.pk)
|
|
||||||
|
|
||||||
# Cannot combine a unique query with a non-unique query -> we have to call distinct
|
|
||||||
return Package.objects.filter(pk__in=accessible_secret).distinct() | non_secret.distinct()
|
|
||||||
|
|
||||||
# EDIT END
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_all_readable_packages(user, include_reviewed=False):
|
def get_all_readable_packages(user, include_reviewed=False):
|
||||||
# UserPermission only exists if at least read is granted...
|
# UserPermission only exists if at least read is granted...
|
||||||
@ -480,13 +470,7 @@ class PackageManager(object):
|
|||||||
# remove package if user is owner and package is reviewed e.g. admin
|
# remove package if user is owner and package is reviewed e.g. admin
|
||||||
qs = qs.filter(reviewed=False)
|
qs = qs.filter(reviewed=False)
|
||||||
|
|
||||||
qs = qs.distinct()
|
return qs.distinct()
|
||||||
|
|
||||||
# EDIT START
|
|
||||||
qs = PackageManager.check_package_classifications(user, qs)
|
|
||||||
# EDIT END
|
|
||||||
|
|
||||||
return qs
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_all_writeable_packages(user):
|
def get_all_writeable_packages(user):
|
||||||
@ -530,13 +514,11 @@ class PackageManager(object):
|
|||||||
|
|
||||||
qs = qs.filter(reviewed=False)
|
qs = qs.filter(reviewed=False)
|
||||||
|
|
||||||
qs = qs.distinct()
|
return qs.distinct()
|
||||||
|
|
||||||
# EDIT START
|
@staticmethod
|
||||||
qs = PackageManager.check_package_classifications(user, qs)
|
def get_packages():
|
||||||
# EDIT END
|
return Package.objects.all()
|
||||||
|
|
||||||
return qs
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
@ -641,25 +623,6 @@ class PackageManager(object):
|
|||||||
else:
|
else:
|
||||||
pack.reviewed = False
|
pack.reviewed = False
|
||||||
|
|
||||||
# EDIT START
|
|
||||||
if data.get("classification"):
|
|
||||||
if data["classification"] == "INTERNAL":
|
|
||||||
pack.classification = Package.Classification.RESTRICTED
|
|
||||||
elif data["classification"] == "RESTRICTED":
|
|
||||||
pack.classification = Package.Classification.RESTRICTED
|
|
||||||
elif data["classification"] == "SECRET":
|
|
||||||
pack.classification = Package.Classification.SECRET
|
|
||||||
|
|
||||||
if not "datapool" in data:
|
|
||||||
raise ValueError("Missing datapool in package")
|
|
||||||
|
|
||||||
g = Group.objects.get(uuid=data["datapool"].split('/')[-1])
|
|
||||||
pack.data_pool = g
|
|
||||||
else:
|
|
||||||
raise ValueError(f"Invalid classification {data['classification']}")
|
|
||||||
|
|
||||||
# EDIT END
|
|
||||||
|
|
||||||
pack.description = data["description"]
|
pack.description = data["description"]
|
||||||
pack.save()
|
pack.save()
|
||||||
|
|
||||||
@ -745,13 +708,7 @@ class PackageManager(object):
|
|||||||
default_structure = None
|
default_structure = None
|
||||||
|
|
||||||
for structure in compound["structures"]:
|
for structure in compound["structures"]:
|
||||||
if structure.get("pesLink"):
|
|
||||||
from bayer.models import PESStructure
|
|
||||||
struc = PESStructure()
|
|
||||||
struc.pes_link = structure["pesLink"]
|
|
||||||
else:
|
|
||||||
struc = CompoundStructure()
|
struc = CompoundStructure()
|
||||||
|
|
||||||
# struc.object_url = Command.get_id(structure, keep_ids)
|
# struc.object_url = Command.get_id(structure, keep_ids)
|
||||||
struc.compound = comp
|
struc.compound = comp
|
||||||
struc.uuid = UUID(structure["id"].split("/")[-1]) if keep_ids else uuid4()
|
struc.uuid = UUID(structure["id"].split("/")[-1]) if keep_ids else uuid4()
|
||||||
@ -759,10 +716,6 @@ class PackageManager(object):
|
|||||||
struc.description = structure["description"]
|
struc.description = structure["description"]
|
||||||
struc.aliases = structure.get("aliases", [])
|
struc.aliases = structure.get("aliases", [])
|
||||||
struc.smiles = structure["smiles"]
|
struc.smiles = structure["smiles"]
|
||||||
|
|
||||||
if structure.get("molfile"):
|
|
||||||
struc.molfile = structure["molfile"]
|
|
||||||
|
|
||||||
struc.save()
|
struc.save()
|
||||||
|
|
||||||
for scen in structure["scenarios"]:
|
for scen in structure["scenarios"]:
|
||||||
@ -1065,9 +1018,52 @@ class PackageManager(object):
|
|||||||
|
|
||||||
print("Fixing Node depths...")
|
print("Fixing Node depths...")
|
||||||
total_pws = Pathway.objects.filter(package=pack).count()
|
total_pws = Pathway.objects.filter(package=pack).count()
|
||||||
|
|
||||||
for p, pw in enumerate(Pathway.objects.filter(package=pack)):
|
for p, pw in enumerate(Pathway.objects.filter(package=pack)):
|
||||||
pw.update_depths()
|
in_count = defaultdict(lambda: 0)
|
||||||
|
out_count = defaultdict(lambda: 0)
|
||||||
|
|
||||||
|
for e in pw.edges:
|
||||||
|
# TODO check if this will remain
|
||||||
|
for react in e.start_nodes.all():
|
||||||
|
out_count[str(react.uuid)] += 1
|
||||||
|
|
||||||
|
for prod in e.end_nodes.all():
|
||||||
|
in_count[str(prod.uuid)] += 1
|
||||||
|
|
||||||
|
root_nodes = []
|
||||||
|
for n in pw.nodes:
|
||||||
|
num_parents = in_count[str(n.uuid)]
|
||||||
|
if num_parents == 0:
|
||||||
|
# must be a root node or unconnected node
|
||||||
|
if n.depth != 0:
|
||||||
|
n.depth = 0
|
||||||
|
n.save()
|
||||||
|
|
||||||
|
# Only root node may have children
|
||||||
|
if out_count[str(n.uuid)] > 0:
|
||||||
|
root_nodes.append(n)
|
||||||
|
|
||||||
|
levels = [root_nodes]
|
||||||
|
seen = set()
|
||||||
|
# Do a bfs to determine depths starting with level 0 a.k.a. root nodes
|
||||||
|
for i, level_nodes in enumerate(levels):
|
||||||
|
new_level = []
|
||||||
|
for n in level_nodes:
|
||||||
|
for e in n.out_edges.all():
|
||||||
|
for prod in e.end_nodes.all():
|
||||||
|
if str(prod.uuid) not in seen:
|
||||||
|
old_depth = prod.depth
|
||||||
|
if old_depth != i + 1:
|
||||||
|
prod.depth = i + 1
|
||||||
|
prod.save()
|
||||||
|
|
||||||
|
new_level.append(prod)
|
||||||
|
|
||||||
|
seen.add(str(n.uuid))
|
||||||
|
|
||||||
|
if new_level:
|
||||||
|
levels.append(new_level)
|
||||||
|
|
||||||
print(f"{p + 1}/{total_pws} fixed.", end="\r")
|
print(f"{p + 1}/{total_pws} fixed.", end="\r")
|
||||||
|
|
||||||
return pack
|
return pack
|
||||||
@ -1078,8 +1074,10 @@ class PackageManager(object):
|
|||||||
data: Dict[str, Any],
|
data: Dict[str, Any],
|
||||||
owner: User,
|
owner: User,
|
||||||
preserve_uuids=False,
|
preserve_uuids=False,
|
||||||
|
add_import_timestamp=True,
|
||||||
|
trust_reviewed=False,
|
||||||
) -> Package:
|
) -> Package:
|
||||||
importer = PackageImporter(data, preserve_uuids)
|
importer = PackageImporter(data, preserve_uuids, add_import_timestamp, trust_reviewed)
|
||||||
imported_package = importer.do_import()
|
imported_package = importer.do_import()
|
||||||
|
|
||||||
up = UserPackagePermission()
|
up = UserPackagePermission()
|
||||||
@ -1896,12 +1894,6 @@ class SPathway(object):
|
|||||||
"to": to_indices,
|
"to": to_indices,
|
||||||
}
|
}
|
||||||
|
|
||||||
if edge.rule:
|
|
||||||
e["rule"] = edge.rule.simple_json()
|
|
||||||
|
|
||||||
if edge.probability:
|
|
||||||
e["probability"] = edge.probability
|
|
||||||
|
|
||||||
edges.append(e)
|
edges.append(e)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@ -99,15 +99,11 @@ class Command(BaseCommand):
|
|||||||
new_license.image_link = f"https://licensebuttons.net/l/{cc_string}/4.0/88x31.png"
|
new_license.image_link = f"https://licensebuttons.net/l/{cc_string}/4.0/88x31.png"
|
||||||
new_license.save()
|
new_license.save()
|
||||||
|
|
||||||
def import_package(self, data, owner, all_envipath_user_group):
|
def import_package(self, data, owner):
|
||||||
p = PackageManager.import_legacy_package(
|
return PackageManager.import_legacy_package(
|
||||||
data, owner, keep_ids=True, add_import_timestamp=False, trust_reviewed=True
|
data, owner, keep_ids=True, add_import_timestamp=False, trust_reviewed=True
|
||||||
)
|
)
|
||||||
|
|
||||||
PackageManager.grant_read(owner, p, all_envipath_user_group)
|
|
||||||
|
|
||||||
return p
|
|
||||||
|
|
||||||
def create_default_setting(self, owner, packages):
|
def create_default_setting(self, owner, packages):
|
||||||
s = SettingManager.create_setting(
|
s = SettingManager.create_setting(
|
||||||
owner,
|
owner,
|
||||||
@ -202,7 +198,7 @@ class Command(BaseCommand):
|
|||||||
s.BASE_DIR / "fixtures" / "packages" / "2025-07-18" / p, encoding="utf-8"
|
s.BASE_DIR / "fixtures" / "packages" / "2025-07-18" / p, encoding="utf-8"
|
||||||
).read()
|
).read()
|
||||||
)
|
)
|
||||||
imported_package = self.import_package(package_data, admin, g)
|
imported_package = self.import_package(package_data, admin)
|
||||||
mapping[p.replace(".json", "")] = imported_package
|
mapping[p.replace(".json", "")] = imported_package
|
||||||
|
|
||||||
setting = self.create_default_setting(admin, [mapping["EAWAG-BBD"]])
|
setting = self.create_default_setting(admin, [mapping["EAWAG-BBD"]])
|
||||||
|
|||||||
@ -1,54 +1,50 @@
|
|||||||
# Generated by Django 6.0.3 on 2026-04-21 11:43
|
# Generated by Django 6.0.3 on 2026-04-14 19:07
|
||||||
|
|
||||||
from django.db import migrations, models
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
("epdb", "0022_alter_classifierpluginmodel_data_packages_and_more"),
|
('epdb', '0022_alter_classifierpluginmodel_data_packages_and_more'),
|
||||||
]
|
]
|
||||||
|
|
||||||
operations = [
|
operations = [
|
||||||
migrations.AlterModelOptions(
|
migrations.AlterModelOptions(
|
||||||
name="compoundstructure",
|
name='compoundstructure',
|
||||||
options={},
|
options={},
|
||||||
),
|
),
|
||||||
migrations.AlterModelOptions(
|
migrations.AlterModelOptions(
|
||||||
name="epmodel",
|
name='epmodel',
|
||||||
options={},
|
options={},
|
||||||
),
|
),
|
||||||
migrations.AlterModelOptions(
|
migrations.AlterModelOptions(
|
||||||
name="parallelrule",
|
name='parallelrule',
|
||||||
options={},
|
options={},
|
||||||
),
|
),
|
||||||
migrations.AlterModelOptions(
|
migrations.AlterModelOptions(
|
||||||
name="rule",
|
name='rule',
|
||||||
options={},
|
options={},
|
||||||
),
|
),
|
||||||
migrations.AlterModelOptions(
|
migrations.AlterModelOptions(
|
||||||
name="sequentialrule",
|
name='sequentialrule',
|
||||||
options={},
|
options={},
|
||||||
),
|
),
|
||||||
migrations.AlterModelOptions(
|
migrations.AlterModelOptions(
|
||||||
name="simpleambitrule",
|
name='simpleambitrule',
|
||||||
options={},
|
options={},
|
||||||
),
|
),
|
||||||
migrations.AlterModelOptions(
|
migrations.AlterModelOptions(
|
||||||
name="simplerdkitrule",
|
name='simplerdkitrule',
|
||||||
options={},
|
options={},
|
||||||
),
|
),
|
||||||
migrations.AlterModelOptions(
|
migrations.AlterModelOptions(
|
||||||
name="simplerule",
|
name='simplerule',
|
||||||
options={},
|
options={},
|
||||||
),
|
),
|
||||||
migrations.AddField(
|
migrations.AddField(
|
||||||
model_name="compoundstructure",
|
model_name='group',
|
||||||
name="molfile",
|
name='secret',
|
||||||
field=models.TextField(blank=True, null=True, verbose_name="Molfile"),
|
field=models.BooleanField(default=False, verbose_name='Secret Group'),
|
||||||
),
|
|
||||||
migrations.AddField(
|
|
||||||
model_name="group",
|
|
||||||
name="secret",
|
|
||||||
field=models.BooleanField(default=False, verbose_name="Secret Group"),
|
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
|
|||||||
@ -1,17 +0,0 @@
|
|||||||
# Generated by Django 6.0.3 on 2026-04-21 19:56
|
|
||||||
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [
|
|
||||||
("epdb", "0023_alter_compoundstructure_options_and_more"),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name="user",
|
|
||||||
name="contacted",
|
|
||||||
field=models.BooleanField(blank=True, null=True),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
@ -1,57 +0,0 @@
|
|||||||
# Generated by Django 6.0.3 on 2026-05-11 20:25
|
|
||||||
|
|
||||||
from django.db import migrations
|
|
||||||
from envipy_additional_information import HalfLife, HalfLifeModel, HalfLifeWS
|
|
||||||
|
|
||||||
MAPPING = {
|
|
||||||
"": HalfLifeModel.OTHER,
|
|
||||||
"HS-SFO": HalfLifeModel.HS_SFO,
|
|
||||||
"FOMC": HalfLifeModel.FOMC,
|
|
||||||
"FOTC": HalfLifeModel.DFOP,
|
|
||||||
"FMOC": HalfLifeModel.FOMC,
|
|
||||||
"DFOP": HalfLifeModel.DFOP,
|
|
||||||
"SFO + SFO": HalfLifeModel.SFO_SFO,
|
|
||||||
"FOMC-SFO": HalfLifeModel.FOMC_SFO,
|
|
||||||
"first order kinetics": HalfLifeModel.SFO,
|
|
||||||
"SFO²": HalfLifeModel.SFO,
|
|
||||||
"HS": HalfLifeModel.HS,
|
|
||||||
"top down": HalfLifeModel.OTHER,
|
|
||||||
"SFO": HalfLifeModel.SFO,
|
|
||||||
"First Order": HalfLifeModel.SFO,
|
|
||||||
"SFO/SFO": HalfLifeModel.SFO_SFO,
|
|
||||||
"FOMC + SFO": HalfLifeModel.FOMC_SFO,
|
|
||||||
"true": HalfLifeModel.SFO,
|
|
||||||
"SFO-SFO": HalfLifeModel.SFO_SFO,
|
|
||||||
"DFOP-SFO": HalfLifeModel.DFOP_SFO,
|
|
||||||
"other": HalfLifeModel.OTHER,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def forward_func(apps, schema_editor):
|
|
||||||
AdditionalInformation = apps.get_model("epdb", "AdditionalInformation")
|
|
||||||
|
|
||||||
hls = AdditionalInformation.objects.filter(type="HalfLife")
|
|
||||||
|
|
||||||
for hl in hls:
|
|
||||||
data = hl.data
|
|
||||||
data["model"] = MAPPING[data["model"]].value
|
|
||||||
hl.data = HalfLife(**data).model_dump(mode="json")
|
|
||||||
hl.save()
|
|
||||||
|
|
||||||
hlws = AdditionalInformation.objects.filter(type="HalfLifeWS")
|
|
||||||
|
|
||||||
for hl in hlws:
|
|
||||||
data = hl.data
|
|
||||||
data["model"] = MAPPING[data["model"]].value
|
|
||||||
hl.data = HalfLifeWS(**data).model_dump(mode="json")
|
|
||||||
hl.save()
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [
|
|
||||||
("epdb", "0024_user_contacted"),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.RunPython(forward_func, reverse_code=migrations.RunPython.noop),
|
|
||||||
]
|
|
||||||
@ -1,48 +0,0 @@
|
|||||||
# Generated by Django 6.0.3 on 2026-06-02 17:18
|
|
||||||
|
|
||||||
from django.db import migrations
|
|
||||||
from envipy_additional_information import DOI
|
|
||||||
|
|
||||||
|
|
||||||
def forward_func(apps, schema_editor):
|
|
||||||
AdditionalInformation = apps.get_model("epdb", "AdditionalInformation")
|
|
||||||
|
|
||||||
refs = AdditionalInformation.objects.filter(type="Reference")
|
|
||||||
|
|
||||||
remaining = []
|
|
||||||
|
|
||||||
for ref in refs:
|
|
||||||
r = ref.data["reference"]
|
|
||||||
try:
|
|
||||||
# PubMed IDs are plain ints, try parsing
|
|
||||||
_ = int(r)
|
|
||||||
# Nothing to do
|
|
||||||
except ValueError:
|
|
||||||
DOMAINS = [
|
|
||||||
"http://dx.doi.org/",
|
|
||||||
"https://dx.doi.org/",
|
|
||||||
"http://doi.org/",
|
|
||||||
"https://doi.org/",
|
|
||||||
]
|
|
||||||
for d in DOMAINS:
|
|
||||||
r = r.replace(d, "")
|
|
||||||
|
|
||||||
if r.startswith("10."):
|
|
||||||
ref.type = DOI.__name__
|
|
||||||
ref.data = {"doi": r}
|
|
||||||
ref.save()
|
|
||||||
else:
|
|
||||||
remaining.append(ref)
|
|
||||||
|
|
||||||
if len(remaining) > 0:
|
|
||||||
raise ValueError(f"Could not parse {len(remaining)} references")
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [
|
|
||||||
("epdb", "0025_auto_20260511_2025"),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.RunPython(forward_func, reverse_code=migrations.RunPython.noop),
|
|
||||||
]
|
|
||||||
@ -1,150 +0,0 @@
|
|||||||
# Generated by Django 6.0.3 on 2026-07-01 20:59
|
|
||||||
|
|
||||||
import django.contrib.postgres.fields
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
dependencies = [
|
|
||||||
("epdb", "0026_auto_20260602_1718"),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="compound",
|
|
||||||
name="aliases",
|
|
||||||
field=django.contrib.postgres.fields.ArrayField(
|
|
||||||
base_field=models.TextField(), blank=True, default=list, verbose_name="Aliases"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="compound",
|
|
||||||
name="default_structure",
|
|
||||||
field=models.ForeignKey(
|
|
||||||
null=True,
|
|
||||||
on_delete=django.db.models.deletion.SET_NULL,
|
|
||||||
related_name="compound_default_structure",
|
|
||||||
to="epdb.compoundstructure",
|
|
||||||
verbose_name="Default Structure",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="compound",
|
|
||||||
name="scenarios",
|
|
||||||
field=models.ManyToManyField(
|
|
||||||
blank=True, to="epdb.scenario", verbose_name="Attached Scenarios"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="compoundstructure",
|
|
||||||
name="aliases",
|
|
||||||
field=django.contrib.postgres.fields.ArrayField(
|
|
||||||
base_field=models.TextField(), blank=True, default=list, verbose_name="Aliases"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="compoundstructure",
|
|
||||||
name="scenarios",
|
|
||||||
field=models.ManyToManyField(
|
|
||||||
blank=True, to="epdb.scenario", verbose_name="Attached Scenarios"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="edge",
|
|
||||||
name="aliases",
|
|
||||||
field=django.contrib.postgres.fields.ArrayField(
|
|
||||||
base_field=models.TextField(), blank=True, default=list, verbose_name="Aliases"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="edge",
|
|
||||||
name="edge_label",
|
|
||||||
field=models.ForeignKey(
|
|
||||||
null=True,
|
|
||||||
on_delete=django.db.models.deletion.CASCADE,
|
|
||||||
to="epdb.reaction",
|
|
||||||
verbose_name="Edge label",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="edge",
|
|
||||||
name="scenarios",
|
|
||||||
field=models.ManyToManyField(
|
|
||||||
blank=True, to="epdb.scenario", verbose_name="Attached Scenarios"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="node",
|
|
||||||
name="aliases",
|
|
||||||
field=django.contrib.postgres.fields.ArrayField(
|
|
||||||
base_field=models.TextField(), blank=True, default=list, verbose_name="Aliases"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="node",
|
|
||||||
name="scenarios",
|
|
||||||
field=models.ManyToManyField(
|
|
||||||
blank=True, to="epdb.scenario", verbose_name="Attached Scenarios"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="pathway",
|
|
||||||
name="aliases",
|
|
||||||
field=django.contrib.postgres.fields.ArrayField(
|
|
||||||
base_field=models.TextField(), blank=True, default=list, verbose_name="Aliases"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="pathway",
|
|
||||||
name="scenarios",
|
|
||||||
field=models.ManyToManyField(
|
|
||||||
blank=True, to="epdb.scenario", verbose_name="Attached Scenarios"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="reaction",
|
|
||||||
name="aliases",
|
|
||||||
field=django.contrib.postgres.fields.ArrayField(
|
|
||||||
base_field=models.TextField(), blank=True, default=list, verbose_name="Aliases"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="reaction",
|
|
||||||
name="medline_references",
|
|
||||||
field=django.contrib.postgres.fields.ArrayField(
|
|
||||||
base_field=models.TextField(),
|
|
||||||
blank=True,
|
|
||||||
null=True,
|
|
||||||
verbose_name="Medline References",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="reaction",
|
|
||||||
name="rules",
|
|
||||||
field=models.ManyToManyField(
|
|
||||||
blank=True, related_name="reaction_rule", to="epdb.rule", verbose_name="Rule"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="reaction",
|
|
||||||
name="scenarios",
|
|
||||||
field=models.ManyToManyField(
|
|
||||||
blank=True, to="epdb.scenario", verbose_name="Attached Scenarios"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="rule",
|
|
||||||
name="aliases",
|
|
||||||
field=django.contrib.postgres.fields.ArrayField(
|
|
||||||
base_field=models.TextField(), blank=True, default=list, verbose_name="Aliases"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
migrations.AlterField(
|
|
||||||
model_name="rule",
|
|
||||||
name="scenarios",
|
|
||||||
field=models.ManyToManyField(
|
|
||||||
blank=True, to="epdb.scenario", verbose_name="Attached Scenarios"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
463
epdb/models.py
@ -31,10 +31,6 @@ from sklearn.model_selection import ShuffleSplit
|
|||||||
|
|
||||||
from bridge.contracts import Property
|
from bridge.contracts import Property
|
||||||
from bridge.dto import RunResult, PropertyPrediction
|
from bridge.dto import RunResult, PropertyPrediction
|
||||||
from epdb.exceptions import (
|
|
||||||
InvalidMolfileException,
|
|
||||||
InvalidSMILESException,
|
|
||||||
)
|
|
||||||
from utilities.chem import FormatConverter, IndigoUtils, PredictionResult, ProductSet
|
from utilities.chem import FormatConverter, IndigoUtils, PredictionResult, ProductSet
|
||||||
from utilities.ml import (
|
from utilities.ml import (
|
||||||
ApplicabilityDomainPCA,
|
ApplicabilityDomainPCA,
|
||||||
@ -79,7 +75,6 @@ class User(AbstractUser):
|
|||||||
blank=False,
|
blank=False,
|
||||||
)
|
)
|
||||||
is_reviewer = models.BooleanField(default=False)
|
is_reviewer = models.BooleanField(default=False)
|
||||||
contacted = models.BooleanField(null=True, blank=True)
|
|
||||||
|
|
||||||
USERNAME_FIELD = "email"
|
USERNAME_FIELD = "email"
|
||||||
REQUIRED_FIELDS = ["username"]
|
REQUIRED_FIELDS = ["username"]
|
||||||
@ -580,10 +575,6 @@ class ReactionIdentifierMixin(ExternalIdentifierMixin):
|
|||||||
def get_uniprot_identifiers(self):
|
def get_uniprot_identifiers(self):
|
||||||
return self.get_external_identifier("UniProt")
|
return self.get_external_identifier("UniProt")
|
||||||
|
|
||||||
def contains_pes(self):
|
|
||||||
from bayer.models import PESStructure
|
|
||||||
return any([isinstance(o, PESStructure) for o in self.educts.all()]) or any(
|
|
||||||
[isinstance(o, PESStructure) for o in self.products.all()])
|
|
||||||
|
|
||||||
##############
|
##############
|
||||||
# EP Objects #
|
# EP Objects #
|
||||||
@ -640,7 +631,7 @@ class EnviPathModel(TimeStampedModel):
|
|||||||
|
|
||||||
class AliasMixin(models.Model):
|
class AliasMixin(models.Model):
|
||||||
aliases = ArrayField(
|
aliases = ArrayField(
|
||||||
models.TextField(blank=False, null=False), verbose_name="Aliases", default=list, blank=True
|
models.TextField(blank=False, null=False), verbose_name="Aliases", default=list
|
||||||
)
|
)
|
||||||
|
|
||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
@ -663,9 +654,7 @@ class AliasMixin(models.Model):
|
|||||||
|
|
||||||
|
|
||||||
class ScenarioMixin(models.Model):
|
class ScenarioMixin(models.Model):
|
||||||
scenarios = models.ManyToManyField(
|
scenarios = models.ManyToManyField("epdb.Scenario", verbose_name="Attached Scenarios")
|
||||||
"epdb.Scenario", verbose_name="Attached Scenarios", blank=True
|
|
||||||
)
|
|
||||||
|
|
||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
def set_scenarios(self, scenarios: List["Scenario"]):
|
def set_scenarios(self, scenarios: List["Scenario"]):
|
||||||
@ -791,19 +780,12 @@ class Compound(
|
|||||||
"CompoundStructure",
|
"CompoundStructure",
|
||||||
verbose_name="Default Structure",
|
verbose_name="Default Structure",
|
||||||
related_name="compound_default_structure",
|
related_name="compound_default_structure",
|
||||||
on_delete=models.SET_NULL,
|
on_delete=models.CASCADE,
|
||||||
null=True,
|
null=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
external_identifiers = GenericRelation("ExternalIdentifier")
|
external_identifiers = GenericRelation("ExternalIdentifier")
|
||||||
|
|
||||||
def get_structure_by_smiles(self, smiles: str) -> "CompoundStructure":
|
|
||||||
for struct in self.structures.all():
|
|
||||||
if struct.smiles == smiles:
|
|
||||||
return struct
|
|
||||||
|
|
||||||
raise ValueError(f"No structure with SMILES {smiles} found for {self.get_name()}")
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def structures(self) -> QuerySet:
|
def structures(self) -> QuerySet:
|
||||||
return CompoundStructure.objects.filter(compound=self)
|
return CompoundStructure.objects.filter(compound=self)
|
||||||
@ -872,79 +854,40 @@ class Compound(
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
def create(
|
def create(
|
||||||
package: "Package",
|
package: "Package", smiles: str, name: str = None, description: str = None, *args, **kwargs
|
||||||
smiles: str,
|
|
||||||
molfile: str | None = None,
|
|
||||||
name: str | None = None,
|
|
||||||
description: str | None = None,
|
|
||||||
*args,
|
|
||||||
**kwargs,
|
|
||||||
) -> "Compound":
|
) -> "Compound":
|
||||||
# Molfile has precendence over SMILES
|
|
||||||
if molfile is not None and molfile.strip() != "":
|
|
||||||
mol = FormatConverter.from_molfile(molfile)
|
|
||||||
|
|
||||||
if mol is None:
|
|
||||||
raise InvalidMolfileException("Given molfile is invalid")
|
|
||||||
else:
|
|
||||||
# Overwrite SMILES from molfile
|
|
||||||
smiles = FormatConverter.to_smiles(mol)
|
|
||||||
|
|
||||||
if smiles is None or smiles.strip() == "":
|
if smiles is None or smiles.strip() == "":
|
||||||
raise InvalidSMILESException("SMILES is required")
|
raise ValueError("SMILES is required")
|
||||||
|
|
||||||
smiles = smiles.strip()
|
smiles = smiles.strip()
|
||||||
|
|
||||||
parsed = FormatConverter.from_smiles(smiles)
|
parsed = FormatConverter.from_smiles(smiles)
|
||||||
if parsed is None:
|
if parsed is None:
|
||||||
raise InvalidSMILESException("Given SMILES is invalid")
|
raise ValueError("Given SMILES is invalid")
|
||||||
|
|
||||||
if name is not None:
|
|
||||||
# Clean for potential XSS
|
|
||||||
name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
|
||||||
|
|
||||||
standardized_smiles = FormatConverter.standardize(smiles, remove_stereo=True)
|
standardized_smiles = FormatConverter.standardize(smiles, remove_stereo=True)
|
||||||
|
|
||||||
subclasses = CompoundStructure.__subclasses__()
|
|
||||||
|
|
||||||
qs = CompoundStructure.objects.filter(smiles=smiles, compound__package=package)
|
|
||||||
if subclasses:
|
|
||||||
qs = qs.not_instance_of(*subclasses)
|
|
||||||
|
|
||||||
# Check if we find a direct match for a given SMILES
|
# Check if we find a direct match for a given SMILES
|
||||||
if qs.exists():
|
if CompoundStructure.objects.filter(smiles=smiles, compound__package=package).exists():
|
||||||
found_structure = qs.first()
|
return CompoundStructure.objects.get(smiles=smiles, compound__package=package).compound
|
||||||
found_compound = found_structure.compound
|
|
||||||
|
|
||||||
if name:
|
|
||||||
found_structure.add_alias(name)
|
|
||||||
found_compound.add_alias(name)
|
|
||||||
|
|
||||||
return found_compound
|
|
||||||
|
|
||||||
qs = CompoundStructure.objects.filter(smiles=standardized_smiles, compound__package=package)
|
|
||||||
if subclasses:
|
|
||||||
qs = qs.not_instance_of(*subclasses)
|
|
||||||
|
|
||||||
# Check if we can find the standardized one
|
# Check if we can find the standardized one
|
||||||
if qs.exists():
|
if CompoundStructure.objects.filter(
|
||||||
found_structure = qs.first()
|
smiles=standardized_smiles, compound__package=package
|
||||||
found_compound = found_structure.compound
|
).exists():
|
||||||
|
# TODO should we add a structure?
|
||||||
# We've only found the standardized one, create the very structure
|
return CompoundStructure.objects.get(
|
||||||
_ = found_compound.add_structure(
|
smiles=standardized_smiles, compound__package=package
|
||||||
smiles, molfile=molfile, name=name, description=description
|
).compound
|
||||||
)
|
|
||||||
|
|
||||||
if name:
|
|
||||||
found_compound.add_alias(name)
|
|
||||||
|
|
||||||
return found_compound
|
|
||||||
|
|
||||||
# Generate Compound
|
# Generate Compound
|
||||||
c = Compound()
|
c = Compound()
|
||||||
c.package = package
|
c.package = package
|
||||||
|
|
||||||
|
if name is not None:
|
||||||
|
# Clean for potential XSS
|
||||||
|
name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
||||||
|
|
||||||
if name is None or name == "":
|
if name is None or name == "":
|
||||||
name = f"Compound {Compound.objects.filter(package=package).count() + 1}"
|
name = f"Compound {Compound.objects.filter(package=package).count() + 1}"
|
||||||
|
|
||||||
@ -968,12 +911,7 @@ class Compound(
|
|||||||
)
|
)
|
||||||
|
|
||||||
cs = CompoundStructure.create(
|
cs = CompoundStructure.create(
|
||||||
c,
|
c, smiles, name=name, description=description, normalized_structure=is_standardized
|
||||||
smiles,
|
|
||||||
molfile=molfile,
|
|
||||||
name=name,
|
|
||||||
description=description,
|
|
||||||
normalized_structure=is_standardized,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
c.default_structure = cs
|
c.default_structure = cs
|
||||||
@ -986,22 +924,11 @@ class Compound(
|
|||||||
self,
|
self,
|
||||||
smiles: str,
|
smiles: str,
|
||||||
name: str = None,
|
name: str = None,
|
||||||
molfile: str = None,
|
|
||||||
description: str = None,
|
description: str = None,
|
||||||
default_structure: bool = False,
|
default_structure: bool = False,
|
||||||
*args,
|
*args,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
) -> "CompoundStructure":
|
) -> "CompoundStructure":
|
||||||
# Molfile has precendence over SMILES
|
|
||||||
if molfile is not None and molfile.strip() != "":
|
|
||||||
mol = FormatConverter.from_molfile(molfile)
|
|
||||||
|
|
||||||
if mol is None:
|
|
||||||
raise InvalidMolfileException("Given molfile is invalid")
|
|
||||||
else:
|
|
||||||
# Overwrite SMILES from molfile
|
|
||||||
smiles = FormatConverter.to_smiles(mol)
|
|
||||||
|
|
||||||
if smiles is None or smiles == "":
|
if smiles is None or smiles == "":
|
||||||
raise ValueError("SMILES is required")
|
raise ValueError("SMILES is required")
|
||||||
|
|
||||||
@ -1021,28 +948,16 @@ class Compound(
|
|||||||
)
|
)
|
||||||
|
|
||||||
if is_standardized:
|
if is_standardized:
|
||||||
CompoundStructure.objects.get(smiles=smiles, compound__package=self.package)
|
CompoundStructure.objects.get(smiles__in=smiles, compound__package=self.package)
|
||||||
|
|
||||||
# Check if we find a direct match for a given SMILES and/or its standardized SMILES
|
# Check if we find a direct match for a given SMILES and/or its standardized SMILES
|
||||||
if CompoundStructure.objects.filter(smiles=smiles, compound__package=self.package).exists():
|
if CompoundStructure.objects.filter(
|
||||||
found_cs = CompoundStructure.objects.get(smiles=smiles, compound__package=self.package)
|
smiles__in=smiles, compound__package=self.package
|
||||||
|
).exists():
|
||||||
if found_cs.molfile is None and (molfile is not None and molfile.strip() != ""):
|
return CompoundStructure.objects.get(smiles__in=smiles, compound__package=self.package)
|
||||||
logger.info(
|
|
||||||
f"Setting molfile for found CompoundStructure(uuid={found_cs.uuid}) as it was empty"
|
|
||||||
)
|
|
||||||
found_cs.molfile = molfile
|
|
||||||
found_cs.save()
|
|
||||||
|
|
||||||
return found_cs
|
|
||||||
|
|
||||||
cs = CompoundStructure.create(
|
cs = CompoundStructure.create(
|
||||||
self,
|
self, smiles, name=name, description=description, normalized_structure=is_standardized
|
||||||
smiles,
|
|
||||||
name=name,
|
|
||||||
molfile=molfile,
|
|
||||||
description=description,
|
|
||||||
normalized_structure=is_standardized,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if default_structure:
|
if default_structure:
|
||||||
@ -1198,7 +1113,6 @@ class CompoundStructure(
|
|||||||
canonical_smiles = models.TextField(blank=False, null=False, verbose_name="Canonical SMILES")
|
canonical_smiles = models.TextField(blank=False, null=False, verbose_name="Canonical SMILES")
|
||||||
inchikey = models.TextField(max_length=27, blank=False, null=False, verbose_name="InChIKey")
|
inchikey = models.TextField(max_length=27, blank=False, null=False, verbose_name="InChIKey")
|
||||||
normalized_structure = models.BooleanField(null=False, blank=False, default=False)
|
normalized_structure = models.BooleanField(null=False, blank=False, default=False)
|
||||||
molfile = models.TextField(blank=True, null=True, verbose_name="Molfile")
|
|
||||||
|
|
||||||
external_identifiers = GenericRelation("ExternalIdentifier")
|
external_identifiers = GenericRelation("ExternalIdentifier")
|
||||||
|
|
||||||
@ -1223,61 +1137,24 @@ class CompoundStructure(
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
def create(
|
def create(
|
||||||
compound: Compound,
|
compound: Compound, smiles: str, name: str = None, description: str = None, *args, **kwargs
|
||||||
smiles: str,
|
|
||||||
molfile: str = None,
|
|
||||||
name: str = None,
|
|
||||||
description: str = None,
|
|
||||||
*args,
|
|
||||||
**kwargs,
|
|
||||||
):
|
):
|
||||||
# Molfile has precendence over SMILES
|
|
||||||
if molfile is not None and molfile.strip() != "":
|
|
||||||
mol = FormatConverter.from_molfile(molfile)
|
|
||||||
|
|
||||||
if mol is None:
|
|
||||||
raise InvalidMolfileException("Given molfile is invalid")
|
|
||||||
else:
|
|
||||||
# Overwrite SMILES from molfile
|
|
||||||
smiles = FormatConverter.to_smiles(mol)
|
|
||||||
|
|
||||||
# Clean for potential XSS
|
|
||||||
if name is not None:
|
|
||||||
name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
|
||||||
|
|
||||||
if CompoundStructure.objects.filter(compound=compound, smiles=smiles).exists():
|
if CompoundStructure.objects.filter(compound=compound, smiles=smiles).exists():
|
||||||
found_cs = CompoundStructure.objects.get(compound=compound, smiles=smiles)
|
return CompoundStructure.objects.get(compound=compound, smiles=smiles)
|
||||||
|
|
||||||
if name:
|
|
||||||
found_cs.add_alias(name)
|
|
||||||
|
|
||||||
if found_cs.molfile is None and (molfile is not None and molfile.strip() != ""):
|
|
||||||
logger.info(
|
|
||||||
f"Setting molfile for found CompoundStructure(uuid={found_cs.uuid}) as it was empty"
|
|
||||||
)
|
|
||||||
found_cs.molfile = molfile
|
|
||||||
found_cs.save()
|
|
||||||
|
|
||||||
return found_cs
|
|
||||||
|
|
||||||
if compound.pk is None:
|
if compound.pk is None:
|
||||||
raise ValueError("Unpersisted Compound! Persist compound first!")
|
raise ValueError("Unpersisted Compound! Persist compound first!")
|
||||||
|
|
||||||
cs = CompoundStructure()
|
cs = CompoundStructure()
|
||||||
|
# Clean for potential XSS
|
||||||
if name is not None:
|
if name is not None:
|
||||||
cs.name = name
|
cs.name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
||||||
|
|
||||||
# We have a default here only set the value if it carries some payload
|
if description is not None:
|
||||||
if description is not None and description.strip() != "":
|
|
||||||
cs.description = nh3.clean(description, tags=s.ALLOWED_HTML_TAGS).strip()
|
cs.description = nh3.clean(description, tags=s.ALLOWED_HTML_TAGS).strip()
|
||||||
|
|
||||||
cs.compound = compound
|
|
||||||
cs.smiles = smiles
|
cs.smiles = smiles
|
||||||
|
cs.compound = compound
|
||||||
# If molfile is not None, it hase to be a valid Molfile as we've survived the parsing check
|
|
||||||
if molfile is not None:
|
|
||||||
cs.molfile = molfile
|
|
||||||
|
|
||||||
if "normalized_structure" in kwargs:
|
if "normalized_structure" in kwargs:
|
||||||
cs.normalized_structure = kwargs["normalized_structure"]
|
cs.normalized_structure = kwargs["normalized_structure"]
|
||||||
@ -1296,8 +1173,6 @@ class CompoundStructure(
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def as_svg(self, width: int = 800, height: int = 400):
|
def as_svg(self, width: int = 800, height: int = 400):
|
||||||
if self.molfile is not None and self.molfile.strip() != "":
|
|
||||||
return IndigoUtils.mol_to_svg(self.molfile, width=width, height=height)
|
|
||||||
return IndigoUtils.mol_to_svg(self.smiles, width=width, height=height)
|
return IndigoUtils.mol_to_svg(self.smiles, width=width, height=height)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -1334,9 +1209,6 @@ class CompoundStructure(
|
|||||||
|
|
||||||
return dict(hls)
|
return dict(hls)
|
||||||
|
|
||||||
def d3_json(self):
|
|
||||||
return {}
|
|
||||||
|
|
||||||
|
|
||||||
class EnzymeLink(EnviPathModel, KEGGIdentifierMixin):
|
class EnzymeLink(EnviPathModel, KEGGIdentifierMixin):
|
||||||
rule = models.ForeignKey("Rule", on_delete=models.CASCADE, db_index=True)
|
rule = models.ForeignKey("Rule", on_delete=models.CASCADE, db_index=True)
|
||||||
@ -1495,9 +1367,6 @@ class SimpleAmbitRule(SimpleRule):
|
|||||||
if not FormatConverter.is_valid_smirks(smirks):
|
if not FormatConverter.is_valid_smirks(smirks):
|
||||||
raise ValueError(f'SMIRKS "{smirks}" is invalid!')
|
raise ValueError(f'SMIRKS "{smirks}" is invalid!')
|
||||||
|
|
||||||
if name is not None:
|
|
||||||
name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
|
||||||
|
|
||||||
query = SimpleAmbitRule.objects.filter(package=package, smirks=smirks)
|
query = SimpleAmbitRule.objects.filter(package=package, smirks=smirks)
|
||||||
|
|
||||||
if reactant_filter_smarts is not None and reactant_filter_smarts.strip() != "":
|
if reactant_filter_smarts is not None and reactant_filter_smarts.strip() != "":
|
||||||
@ -1509,17 +1378,14 @@ class SimpleAmbitRule(SimpleRule):
|
|||||||
if query.exists():
|
if query.exists():
|
||||||
if query.count() > 1:
|
if query.count() > 1:
|
||||||
logger.error(f"More than one rule matched this one! {query}")
|
logger.error(f"More than one rule matched this one! {query}")
|
||||||
|
return query.first()
|
||||||
found_rule = query.first()
|
|
||||||
|
|
||||||
if name:
|
|
||||||
found_rule.add_alias(name)
|
|
||||||
|
|
||||||
return found_rule
|
|
||||||
|
|
||||||
r = SimpleAmbitRule()
|
r = SimpleAmbitRule()
|
||||||
r.package = package
|
r.package = package
|
||||||
|
|
||||||
|
if name is not None:
|
||||||
|
name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
||||||
|
|
||||||
if name is None or name == "":
|
if name is None or name == "":
|
||||||
name = f"Rule {Rule.objects.filter(package=package).count() + 1}"
|
name = f"Rule {Rule.objects.filter(package=package).count() + 1}"
|
||||||
|
|
||||||
@ -1652,9 +1518,6 @@ class ParallelRule(Rule):
|
|||||||
f"Simple rule {sr.uuid} does not belong to package {package.uuid}!"
|
f"Simple rule {sr.uuid} does not belong to package {package.uuid}!"
|
||||||
)
|
)
|
||||||
|
|
||||||
if name is not None:
|
|
||||||
name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
|
||||||
|
|
||||||
# Deduplication check
|
# Deduplication check
|
||||||
query = ParallelRule.objects.annotate(
|
query = ParallelRule.objects.annotate(
|
||||||
srs_count=Count("simple_rules", filter=Q(simple_rules__in=simple_rules), distinct=True)
|
srs_count=Count("simple_rules", filter=Q(simple_rules__in=simple_rules), distinct=True)
|
||||||
@ -1666,19 +1529,15 @@ class ParallelRule(Rule):
|
|||||||
|
|
||||||
if existing_rule_qs.exists():
|
if existing_rule_qs.exists():
|
||||||
if existing_rule_qs.count() > 1:
|
if existing_rule_qs.count() > 1:
|
||||||
logger.error(
|
logger.error(f"Found more than one reaction for given input! {existing_rule_qs}")
|
||||||
f"Found more than one ParallelRule for given input! {existing_rule_qs}"
|
return existing_rule_qs.first()
|
||||||
)
|
|
||||||
|
|
||||||
found_rule = existing_rule_qs.first()
|
|
||||||
if name:
|
|
||||||
found_rule.add_alias(name)
|
|
||||||
|
|
||||||
return found_rule
|
|
||||||
|
|
||||||
r = ParallelRule()
|
r = ParallelRule()
|
||||||
r.package = package
|
r.package = package
|
||||||
|
|
||||||
|
if name is not None:
|
||||||
|
name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
||||||
|
|
||||||
if name is None or name == "":
|
if name is None or name == "":
|
||||||
name = f"Rule {Rule.objects.filter(package=package).count() + 1}"
|
name = f"Rule {Rule.objects.filter(package=package).count() + 1}"
|
||||||
|
|
||||||
@ -1747,15 +1606,10 @@ class Reaction(
|
|||||||
products = models.ManyToManyField(
|
products = models.ManyToManyField(
|
||||||
"epdb.CompoundStructure", verbose_name="Products", related_name="reaction_products"
|
"epdb.CompoundStructure", verbose_name="Products", related_name="reaction_products"
|
||||||
)
|
)
|
||||||
rules = models.ManyToManyField(
|
rules = models.ManyToManyField("epdb.Rule", verbose_name="Rule", related_name="reaction_rule")
|
||||||
"epdb.Rule", verbose_name="Rule", related_name="reaction_rule", blank=True
|
|
||||||
)
|
|
||||||
multi_step = models.BooleanField(verbose_name="Multistep Reaction")
|
multi_step = models.BooleanField(verbose_name="Multistep Reaction")
|
||||||
medline_references = ArrayField(
|
medline_references = ArrayField(
|
||||||
models.TextField(blank=False, null=False),
|
models.TextField(blank=False, null=False), null=True, verbose_name="Medline References"
|
||||||
null=True,
|
|
||||||
verbose_name="Medline References",
|
|
||||||
blank=True,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
external_identifiers = GenericRelation("ExternalIdentifier")
|
external_identifiers = GenericRelation("ExternalIdentifier")
|
||||||
@ -1772,12 +1626,8 @@ class Reaction(
|
|||||||
educts: Union[List[str], List[CompoundStructure]] = None,
|
educts: Union[List[str], List[CompoundStructure]] = None,
|
||||||
products: Union[List[str], List[CompoundStructure]] = None,
|
products: Union[List[str], List[CompoundStructure]] = None,
|
||||||
rules: Union[Rule | List[Rule]] = None,
|
rules: Union[Rule | List[Rule]] = None,
|
||||||
multi_step: bool = False,
|
multi_step: bool = True,
|
||||||
):
|
):
|
||||||
# Clean for potential XSS
|
|
||||||
if name is not None and name.strip() != "":
|
|
||||||
name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
|
||||||
|
|
||||||
_educts = []
|
_educts = []
|
||||||
_products = []
|
_products = []
|
||||||
|
|
||||||
@ -1832,23 +1682,16 @@ class Reaction(
|
|||||||
logger.error(
|
logger.error(
|
||||||
f"Found more than one reaction for given input! {existing_reaction_qs}"
|
f"Found more than one reaction for given input! {existing_reaction_qs}"
|
||||||
)
|
)
|
||||||
|
return existing_reaction_qs.first()
|
||||||
found_reaction = existing_reaction_qs.first()
|
|
||||||
|
|
||||||
if name:
|
|
||||||
found_reaction.add_alias(name)
|
|
||||||
|
|
||||||
return found_reaction
|
|
||||||
|
|
||||||
r = Reaction()
|
r = Reaction()
|
||||||
r.package = package
|
r.package = package
|
||||||
|
|
||||||
if name is None or name == "":
|
# Clean for potential XSS
|
||||||
name = f"Reaction {Reaction.objects.filter(package=package).count() + 1}"
|
if name is not None and name.strip() != "":
|
||||||
|
r.name = nh3.clean(name, tags=s.ALLOWED_HTML_TAGS).strip()
|
||||||
|
|
||||||
r.name = name
|
if description is not None and name.strip() != "":
|
||||||
|
|
||||||
if description is not None and description.strip() != "":
|
|
||||||
r.description = nh3.clean(description, tags=s.ALLOWED_HTML_TAGS).strip()
|
r.description = nh3.clean(description, tags=s.ALLOWED_HTML_TAGS).strip()
|
||||||
|
|
||||||
r.multi_step = multi_step
|
r.multi_step = multi_step
|
||||||
@ -1926,7 +1769,7 @@ class Reaction(
|
|||||||
return new_reaction
|
return new_reaction
|
||||||
|
|
||||||
def smirks(self):
|
def smirks(self):
|
||||||
return f"{'.'.join([cs.smiles for cs in self.educts.all().order_by('-pk')])}>>{'.'.join([cs.smiles for cs in self.products.all().order_by('-pk')])}"
|
return f"{'.'.join([cs.smiles for cs in self.educts.all()])}>>{'.'.join([cs.smiles for cs in self.products.all()])}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def as_svg(self):
|
def as_svg(self):
|
||||||
@ -2039,9 +1882,6 @@ class Pathway(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMix
|
|||||||
if n not in queue:
|
if n not in queue:
|
||||||
queue.append(n)
|
queue.append(n)
|
||||||
|
|
||||||
for i in queue:
|
|
||||||
processed.add(i)
|
|
||||||
|
|
||||||
while len(queue):
|
while len(queue):
|
||||||
current = queue.pop()
|
current = queue.pop()
|
||||||
processed.add(current)
|
processed.add(current)
|
||||||
@ -2082,7 +1922,6 @@ class Pathway(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMix
|
|||||||
# add links start -> pseudo
|
# add links start -> pseudo
|
||||||
new_link = {
|
new_link = {
|
||||||
"name": link["name"],
|
"name": link["name"],
|
||||||
"plain_name": link["plain_name"],
|
|
||||||
"id": link["id"],
|
"id": link["id"],
|
||||||
"url": link["url"],
|
"url": link["url"],
|
||||||
"image": link["image"],
|
"image": link["image"],
|
||||||
@ -2092,7 +1931,6 @@ class Pathway(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMix
|
|||||||
"source": node_url_to_idx[link["start_node_urls"][0]],
|
"source": node_url_to_idx[link["start_node_urls"][0]],
|
||||||
"target": pseudo_idx,
|
"target": pseudo_idx,
|
||||||
"app_domain": link.get("app_domain", None),
|
"app_domain": link.get("app_domain", None),
|
||||||
"to_pseudo": True,
|
|
||||||
}
|
}
|
||||||
adjusted_links.append(new_link)
|
adjusted_links.append(new_link)
|
||||||
|
|
||||||
@ -2100,7 +1938,6 @@ class Pathway(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMix
|
|||||||
for target in link["end_node_urls"]:
|
for target in link["end_node_urls"]:
|
||||||
new_link = {
|
new_link = {
|
||||||
"name": link["name"],
|
"name": link["name"],
|
||||||
"plain_name": link["plain_name"],
|
|
||||||
"id": link["id"],
|
"id": link["id"],
|
||||||
"url": link["url"],
|
"url": link["url"],
|
||||||
"image": link["image"],
|
"image": link["image"],
|
||||||
@ -2111,7 +1948,6 @@ class Pathway(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMix
|
|||||||
"target": node_url_to_idx[target],
|
"target": node_url_to_idx[target],
|
||||||
"app_domain": link.get("app_domain", None),
|
"app_domain": link.get("app_domain", None),
|
||||||
"multi_step": link["multi_step"],
|
"multi_step": link["multi_step"],
|
||||||
"from_pseudo": True,
|
|
||||||
}
|
}
|
||||||
adjusted_links.append(new_link)
|
adjusted_links.append(new_link)
|
||||||
|
|
||||||
@ -2321,12 +2157,11 @@ class Pathway(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMix
|
|||||||
def add_node(
|
def add_node(
|
||||||
self,
|
self,
|
||||||
smiles: str,
|
smiles: str,
|
||||||
molfile: str | None = None,
|
name: Optional[str] = None,
|
||||||
name: str | None = None,
|
description: Optional[str] = None,
|
||||||
description: str | None = None,
|
depth: Optional[int] = 0,
|
||||||
depth: int = -1,
|
|
||||||
):
|
):
|
||||||
return Node.create(self, smiles, depth, molfile=molfile, name=name, description=description)
|
return Node.create(self, smiles, depth, name=name, description=description)
|
||||||
|
|
||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
def add_edge(
|
def add_edge(
|
||||||
@ -2339,68 +2174,6 @@ class Pathway(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMix
|
|||||||
):
|
):
|
||||||
return Edge.create(self, start_nodes, end_nodes, rule, name=name, description=description)
|
return Edge.create(self, start_nodes, end_nodes, rule, name=name, description=description)
|
||||||
|
|
||||||
def update_depths(self):
|
|
||||||
# Collect number of in and out links per node
|
|
||||||
in_count = defaultdict(lambda: 0)
|
|
||||||
out_count = defaultdict(lambda: 0)
|
|
||||||
|
|
||||||
for e in self.edges:
|
|
||||||
for react in e.start_nodes.all():
|
|
||||||
out_count[str(react.uuid)] += 1
|
|
||||||
|
|
||||||
for prod in e.end_nodes.all():
|
|
||||||
in_count[str(prod.uuid)] += 1
|
|
||||||
|
|
||||||
depth_map = {}
|
|
||||||
depth_map[0] = list()
|
|
||||||
processed = set()
|
|
||||||
|
|
||||||
data_driven_root_nodes = (
|
|
||||||
self.node_set.all()
|
|
||||||
.annotate(prod_cnt=Count("edge_products"), educt_cnt=Count("edge_educts"))
|
|
||||||
.filter(prod_cnt=0, educt_cnt__gt=0)
|
|
||||||
.distinct()
|
|
||||||
)
|
|
||||||
|
|
||||||
# Eval QuerySet
|
|
||||||
root_nodes_by_depth = list(self.root_nodes)
|
|
||||||
|
|
||||||
data_driven_root_nodes.update(depth=0)
|
|
||||||
root_nodes = [n for n in data_driven_root_nodes]
|
|
||||||
|
|
||||||
for n in root_nodes_by_depth:
|
|
||||||
if n not in root_nodes:
|
|
||||||
if len(n.edge_products.all()) == 0:
|
|
||||||
root_nodes.append(n)
|
|
||||||
|
|
||||||
for n in root_nodes:
|
|
||||||
depth_map[0].append(n)
|
|
||||||
|
|
||||||
# At most depth len(nodes) is possible
|
|
||||||
for i in range(self.nodes.count()):
|
|
||||||
level_nodes = depth_map.get(i, [])
|
|
||||||
|
|
||||||
if len(level_nodes) == 0:
|
|
||||||
break
|
|
||||||
|
|
||||||
unique_next_level = set()
|
|
||||||
for n in level_nodes:
|
|
||||||
processed.add(n)
|
|
||||||
for e in self.edges:
|
|
||||||
if n in e.start_nodes.all():
|
|
||||||
for p in e.end_nodes.all():
|
|
||||||
if p not in processed:
|
|
||||||
unique_next_level.add(p)
|
|
||||||
|
|
||||||
if len(unique_next_level) > 0:
|
|
||||||
depth_map[i + 1] = list(unique_next_level)
|
|
||||||
|
|
||||||
for depth, nodes in depth_map.items():
|
|
||||||
for n in nodes:
|
|
||||||
if n.depth != depth and depth != 0:
|
|
||||||
n.depth = depth
|
|
||||||
n.save()
|
|
||||||
|
|
||||||
|
|
||||||
class Node(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin):
|
class Node(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin):
|
||||||
pathway = models.ForeignKey(
|
pathway = models.ForeignKey(
|
||||||
@ -2422,19 +2195,17 @@ class Node(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin)
|
|||||||
def _url(self):
|
def _url(self):
|
||||||
return "{}/node/{}".format(self.pathway.url, self.uuid)
|
return "{}/node/{}".format(self.pathway.url, self.uuid)
|
||||||
|
|
||||||
def get_name(self, include_suffix=True):
|
def get_name(self):
|
||||||
non_generic_name = True
|
non_generic_name = True
|
||||||
|
|
||||||
if self.name is None or self.name == "no name":
|
if self.name == "no name":
|
||||||
non_generic_name = False
|
non_generic_name = False
|
||||||
|
|
||||||
if non_generic_name:
|
return (
|
||||||
return self.name
|
self.name
|
||||||
else:
|
if non_generic_name
|
||||||
if include_suffix:
|
else f"{self.default_node_label.name} (taken from underlying structure)"
|
||||||
return f"{self.default_node_label.name} (taken from underlying structure)"
|
)
|
||||||
else:
|
|
||||||
return self.default_node_label.name
|
|
||||||
|
|
||||||
def d3_json(self):
|
def d3_json(self):
|
||||||
app_domain_data = self.get_app_domain_assessment_data()
|
app_domain_data = self.get_app_domain_assessment_data()
|
||||||
@ -2444,27 +2215,16 @@ class Node(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin)
|
|||||||
if isinstance(ai.get(), PropertyPrediction):
|
if isinstance(ai.get(), PropertyPrediction):
|
||||||
predicted_properties[ai.get().__class__.__name__].append(ai.data)
|
predicted_properties[ai.get().__class__.__name__].append(ai.data)
|
||||||
|
|
||||||
# If we have Subclasses of a CompoundStructure we can overwrite keys (e.g. images)
|
return {
|
||||||
# by overwriting keys
|
|
||||||
structure_data = self.default_node_label.d3_json()
|
|
||||||
|
|
||||||
res = {
|
|
||||||
"depth": self.depth,
|
"depth": self.depth,
|
||||||
"stereo_removed": self.stereo_removed,
|
"stereo_removed": self.stereo_removed,
|
||||||
"url": self.url,
|
"url": self.url,
|
||||||
"node_label_id": self.default_node_label.url,
|
"node_label_id": self.default_node_label.url,
|
||||||
"image": f"{self.url}?image=svg",
|
"image": f"{self.url}?image=svg",
|
||||||
"image_svg": IndigoUtils.mol_to_svg(
|
"image_svg": IndigoUtils.mol_to_svg(
|
||||||
self.default_node_label.molfile
|
self.default_node_label.smiles, width=40, height=40
|
||||||
if self.default_node_label.molfile is not None
|
|
||||||
and self.default_node_label.molfile.strip()
|
|
||||||
else self.default_node_label.smiles,
|
|
||||||
width=40,
|
|
||||||
height=40,
|
|
||||||
),
|
),
|
||||||
"image_type": "svg",
|
|
||||||
"name": self.get_name(),
|
"name": self.get_name(),
|
||||||
"plain_name": self.get_name(include_suffix=False),
|
|
||||||
"smiles": self.default_node_label.smiles,
|
"smiles": self.default_node_label.smiles,
|
||||||
"scenarios": [{"name": s.get_name(), "url": s.url} for s in self.scenarios.all()],
|
"scenarios": [{"name": s.get_name(), "url": s.url} for s in self.scenarios.all()],
|
||||||
"app_domain": {
|
"app_domain": {
|
||||||
@ -2475,73 +2235,49 @@ class Node(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin)
|
|||||||
},
|
},
|
||||||
"predicted_properties": predicted_properties,
|
"predicted_properties": predicted_properties,
|
||||||
"is_engineered_intermediate": self.kv.get("is_engineered_intermediate", False),
|
"is_engineered_intermediate": self.kv.get("is_engineered_intermediate", False),
|
||||||
"proposed": self.get_proposed_info(),
|
|
||||||
"timeseries": self.get_timeseries_data(),
|
"timeseries": self.get_timeseries_data(),
|
||||||
**structure_data,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return res
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
def create(
|
def create(
|
||||||
pathway: "Pathway",
|
pathway: "Pathway",
|
||||||
smiles: str,
|
smiles: str,
|
||||||
depth: int,
|
depth: int,
|
||||||
molfile: str | None = None,
|
name: Optional[str] = None,
|
||||||
name: str | None = None,
|
description: Optional[str] = None,
|
||||||
description: str | None = None,
|
|
||||||
):
|
):
|
||||||
# Molfile has precendence over SMILES
|
|
||||||
if molfile is not None and molfile.strip() != "":
|
|
||||||
mol = FormatConverter.from_molfile(molfile)
|
|
||||||
|
|
||||||
if mol is None:
|
|
||||||
raise InvalidMolfileException("Given molfile is invalid")
|
|
||||||
else:
|
|
||||||
# Overwrite SMILES from molfile
|
|
||||||
smiles = FormatConverter.to_smiles(mol)
|
|
||||||
|
|
||||||
stereo_removed = False
|
stereo_removed = False
|
||||||
if pathway.predicted and FormatConverter.has_stereo(smiles):
|
if pathway.predicted and FormatConverter.has_stereo(smiles):
|
||||||
smiles = FormatConverter.standardize(smiles, remove_stereo=True)
|
smiles = FormatConverter.standardize(smiles, remove_stereo=True)
|
||||||
stereo_removed = True
|
stereo_removed = True
|
||||||
|
|
||||||
c = Compound.create(
|
c = Compound.create(pathway.package, smiles, name=name, description=description)
|
||||||
pathway.package, smiles, molfile=molfile, name=name, description=description
|
|
||||||
)
|
|
||||||
|
|
||||||
structure = c.get_structure_by_smiles(smiles)
|
if Node.objects.filter(pathway=pathway, default_node_label=c.default_structure).exists():
|
||||||
|
return Node.objects.get(pathway=pathway, default_node_label=c.default_structure)
|
||||||
if Node.objects.filter(pathway=pathway, default_node_label=structure).exists():
|
|
||||||
return Node.objects.get(pathway=pathway, default_node_label=structure)
|
|
||||||
|
|
||||||
n = Node()
|
n = Node()
|
||||||
n.stereo_removed = stereo_removed
|
n.stereo_removed = stereo_removed
|
||||||
n.pathway = pathway
|
n.pathway = pathway
|
||||||
n.depth = depth
|
n.depth = depth
|
||||||
|
|
||||||
n.default_node_label = structure
|
n.default_node_label = c.default_structure
|
||||||
n.save()
|
n.save()
|
||||||
|
|
||||||
n.node_labels.add(structure)
|
n.node_labels.add(c.default_structure)
|
||||||
n.save()
|
n.save()
|
||||||
|
|
||||||
return n
|
return n
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def as_svg(self):
|
def as_svg(self):
|
||||||
if (
|
|
||||||
self.default_node_label.molfile is not None
|
|
||||||
and self.default_node_label.molfile.strip() != ""
|
|
||||||
):
|
|
||||||
return IndigoUtils.mol_to_svg(self.default_node_label.molfile)
|
|
||||||
return IndigoUtils.mol_to_svg(self.default_node_label.smiles)
|
return IndigoUtils.mol_to_svg(self.default_node_label.smiles)
|
||||||
|
|
||||||
def get_timeseries_data(self):
|
def get_timeseries_data(self):
|
||||||
for ai in self.additional_information.all():
|
for ai in self.additional_information.all():
|
||||||
if ai.type == "OECD301FTimeSeries":
|
if ai.__class__.__name__ == "OECD301FTimeSeries":
|
||||||
return ai.get().model_dump(mode="json")
|
return ai.model_dump(mode="json")
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@ -2572,35 +2308,13 @@ class Node(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin)
|
|||||||
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
def get_proposed_info(self):
|
|
||||||
collected = defaultdict(dict)
|
|
||||||
for ai in self.additional_information.filter(
|
|
||||||
type__in=["ProposedIntermediate", "TransformationProductImportance", "Confidence"],
|
|
||||||
scenario__isnull=False,
|
|
||||||
):
|
|
||||||
collected[str(ai.scenario.uuid)]["scenarioId"] = ai.scenario.url
|
|
||||||
collected[str(ai.scenario.uuid)]["scenarioName"] = ai.scenario.name
|
|
||||||
|
|
||||||
if ai.type == "ProposedIntermediate":
|
|
||||||
collected[str(ai.scenario.uuid)]["proposed"] = True
|
|
||||||
|
|
||||||
if ai.type == "Confidence":
|
|
||||||
collected[str(ai.scenario.uuid)]["Confidence"] = ai.get().level
|
|
||||||
|
|
||||||
if ai.type == "TransformationProductImportance":
|
|
||||||
collected[str(ai.scenario.uuid)]["Transformation product importance"] = (
|
|
||||||
ai.get().importance.value
|
|
||||||
)
|
|
||||||
|
|
||||||
return list(collected.values())
|
|
||||||
|
|
||||||
|
|
||||||
class Edge(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin):
|
class Edge(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin):
|
||||||
pathway = models.ForeignKey(
|
pathway = models.ForeignKey(
|
||||||
"epdb.Pathway", verbose_name="belongs to", on_delete=models.CASCADE, db_index=True
|
"epdb.Pathway", verbose_name="belongs to", on_delete=models.CASCADE, db_index=True
|
||||||
)
|
)
|
||||||
edge_label = models.ForeignKey(
|
edge_label = models.ForeignKey(
|
||||||
"epdb.Reaction", verbose_name="Edge label", null=True, on_delete=models.CASCADE
|
"epdb.Reaction", verbose_name="Edge label", null=True, on_delete=models.SET_NULL
|
||||||
)
|
)
|
||||||
start_nodes = models.ManyToManyField(
|
start_nodes = models.ManyToManyField(
|
||||||
"epdb.Node", verbose_name="Start Nodes", related_name="edge_educts"
|
"epdb.Node", verbose_name="Start Nodes", related_name="edge_educts"
|
||||||
@ -2615,7 +2329,6 @@ class Edge(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin)
|
|||||||
def d3_json(self):
|
def d3_json(self):
|
||||||
edge_json = {
|
edge_json = {
|
||||||
"name": self.get_name(),
|
"name": self.get_name(),
|
||||||
"plain_name": self.get_name(include_suffix=False),
|
|
||||||
"id": self.url,
|
"id": self.url,
|
||||||
"url": self.url,
|
"url": self.url,
|
||||||
"image": self.url + "?image=svg",
|
"image": self.url + "?image=svg",
|
||||||
@ -2680,8 +2393,6 @@ class Edge(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin)
|
|||||||
rule: Optional[Rule] = None,
|
rule: Optional[Rule] = None,
|
||||||
name: Optional[str] = None,
|
name: Optional[str] = None,
|
||||||
description: Optional[str] = None,
|
description: Optional[str] = None,
|
||||||
*args,
|
|
||||||
**kwargs,
|
|
||||||
):
|
):
|
||||||
e = Edge()
|
e = Edge()
|
||||||
e.pathway = pathway
|
e.pathway = pathway
|
||||||
@ -2711,7 +2422,7 @@ class Edge(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin)
|
|||||||
educts=[n.default_node_label for n in e.start_nodes.all()],
|
educts=[n.default_node_label for n in e.start_nodes.all()],
|
||||||
products=[n.default_node_label for n in e.end_nodes.all()],
|
products=[n.default_node_label for n in e.end_nodes.all()],
|
||||||
rules=rule,
|
rules=rule,
|
||||||
multi_step=kwargs.get("multi_step", False),
|
multi_step=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
e.edge_label = r
|
e.edge_label = r
|
||||||
@ -2730,19 +2441,17 @@ class Edge(EnviPathModel, AliasMixin, ScenarioMixin, AdditionalInformationMixin)
|
|||||||
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
def get_name(self, include_suffix=True):
|
def get_name(self):
|
||||||
non_generic_name = True
|
non_generic_name = True
|
||||||
|
|
||||||
if self.name == "no name":
|
if self.name == "no name":
|
||||||
non_generic_name = False
|
non_generic_name = False
|
||||||
|
|
||||||
if non_generic_name:
|
return (
|
||||||
return self.name
|
self.name
|
||||||
else:
|
if non_generic_name
|
||||||
if include_suffix:
|
else f"{self.edge_label.name} (taken from underlying reaction)"
|
||||||
return f"{self.edge_label.name} (taken from underlying reaction)"
|
)
|
||||||
else:
|
|
||||||
return self.edge_label.name
|
|
||||||
|
|
||||||
|
|
||||||
class EPModel(PolymorphicModel, EnviPathModel, AdditionalInformationMixin):
|
class EPModel(PolymorphicModel, EnviPathModel, AdditionalInformationMixin):
|
||||||
@ -4721,22 +4430,18 @@ class AdditionalInformation(models.Model):
|
|||||||
|
|
||||||
return f"{self.scenario.url}/additional-information/{self.uuid}"
|
return f"{self.scenario.url}/additional-information/{self.uuid}"
|
||||||
|
|
||||||
@staticmethod
|
def get(self) -> "EnviPyModel":
|
||||||
def from_dict(ai_type: str, ai_data: Dict[str, Any]):
|
|
||||||
from envipy_additional_information import registry
|
from envipy_additional_information import registry
|
||||||
|
|
||||||
MAPPING = {c.__name__: c for c in registry.list_models().values()}
|
MAPPING = {c.__name__: c for c in registry.list_models().values()}
|
||||||
try:
|
try:
|
||||||
inst = MAPPING[ai_type](**ai_data)
|
inst = MAPPING[self.type](**self.data)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error loading {ai_type}: {e}")
|
print(f"Error loading {self.type}: {e}")
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
return inst
|
|
||||||
|
|
||||||
def get(self) -> "EnviPyModel":
|
|
||||||
inst = AdditionalInformation.from_dict(self.type, self.data)
|
|
||||||
inst.__dict__["uuid"] = str(self.uuid)
|
inst.__dict__["uuid"] = str(self.uuid)
|
||||||
|
|
||||||
return inst
|
return inst
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
|
|||||||
131
epdb/views.py
@ -19,7 +19,6 @@ from sentry_sdk import capture_exception
|
|||||||
|
|
||||||
from utilities.chem import FormatConverter, IndigoUtils
|
from utilities.chem import FormatConverter, IndigoUtils
|
||||||
from utilities.decorators import package_permission_required
|
from utilities.decorators import package_permission_required
|
||||||
from .exceptions import InvalidMolfileException, InvalidSMILESException
|
|
||||||
|
|
||||||
from .logic import (
|
from .logic import (
|
||||||
EPDBURLParser,
|
EPDBURLParser,
|
||||||
@ -389,9 +388,6 @@ def get_base_context(request, for_user=None) -> Dict[str, Any]:
|
|||||||
"debug": s.DEBUG,
|
"debug": s.DEBUG,
|
||||||
"external_databases": ExternalDatabase.get_databases(),
|
"external_databases": ExternalDatabase.get_databases(),
|
||||||
"site_id": s.MATOMO_SITE_ID,
|
"site_id": s.MATOMO_SITE_ID,
|
||||||
# EDIT START
|
|
||||||
"secret_groups": Group.objects.filter(secret=True),
|
|
||||||
# EDIT END
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -786,11 +782,6 @@ def models(request):
|
|||||||
{"Model": s.SERVER_URL + "/model"},
|
{"Model": s.SERVER_URL + "/model"},
|
||||||
]
|
]
|
||||||
|
|
||||||
context["entity_type"] = "model"
|
|
||||||
context["api_endpoint"] = f"{s.SERVER_PATH}/api/v1/models/"
|
|
||||||
context["per_page"] = s.API_PAGINATION_DEFAULT_PAGE_SIZE
|
|
||||||
context["list_title"] = "models"
|
|
||||||
|
|
||||||
# Keep model_types for potential modal/action use
|
# Keep model_types for potential modal/action use
|
||||||
context["model_types"] = {
|
context["model_types"] = {
|
||||||
"ML Relative Reasoning": {
|
"ML Relative Reasoning": {
|
||||||
@ -803,13 +794,11 @@ def models(request):
|
|||||||
"requires_rule_packages": True,
|
"requires_rule_packages": True,
|
||||||
"requires_data_packages": True,
|
"requires_data_packages": True,
|
||||||
},
|
},
|
||||||
}
|
"EnviFormer": {
|
||||||
|
|
||||||
if s.ENVIFORMER_PRESENT:
|
|
||||||
context["model_types"]["EnviFormer"] = {
|
|
||||||
"type": "enviformer",
|
"type": "enviformer",
|
||||||
"requires_rule_packages": False,
|
"requires_rule_packages": False,
|
||||||
"requires_data_packages": True,
|
"requires_data_packages": True,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if s.FLAGS.get("PLUGINS", False):
|
if s.FLAGS.get("PLUGINS", False):
|
||||||
@ -818,9 +807,6 @@ def models(request):
|
|||||||
"type": k,
|
"type": k,
|
||||||
"requires_rule_packages": v.requires_rule_packages(),
|
"requires_rule_packages": v.requires_rule_packages(),
|
||||||
"requires_data_packages": v.requires_data_packages(),
|
"requires_data_packages": v.requires_data_packages(),
|
||||||
"additional_parameters": v.Config.__name__.lower()
|
|
||||||
if v.Config.__name__ != ""
|
|
||||||
else None,
|
|
||||||
}
|
}
|
||||||
for k, v in s.PROPERTY_PLUGINS.items():
|
for k, v in s.PROPERTY_PLUGINS.items():
|
||||||
context["model_types"][v.display()] = {
|
context["model_types"][v.display()] = {
|
||||||
@ -829,6 +815,12 @@ def models(request):
|
|||||||
"requires_data_packages": v.requires_data_packages(),
|
"requires_data_packages": v.requires_data_packages(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Context for paginated template
|
||||||
|
context["entity_type"] = "model"
|
||||||
|
context["api_endpoint"] = f"{s.SERVER_PATH}/api/v1/models/"
|
||||||
|
context["per_page"] = s.API_PAGINATION_DEFAULT_PAGE_SIZE
|
||||||
|
context["list_title"] = "models"
|
||||||
|
|
||||||
return render(request, "collections/models_paginated.html", context)
|
return render(request, "collections/models_paginated.html", context)
|
||||||
|
|
||||||
elif request.method == "POST":
|
elif request.method == "POST":
|
||||||
@ -942,12 +934,11 @@ def package_models(request, package_uuid):
|
|||||||
"requires_rule_packages": True,
|
"requires_rule_packages": True,
|
||||||
"requires_data_packages": True,
|
"requires_data_packages": True,
|
||||||
},
|
},
|
||||||
}
|
"EnviFormer": {
|
||||||
if s.ENVIFORMER_PRESENT:
|
|
||||||
context["model_types"]["EnviFormer"] = {
|
|
||||||
"type": "enviformer",
|
"type": "enviformer",
|
||||||
"requires_rule_packages": False,
|
"requires_rule_packages": False,
|
||||||
"requires_data_packages": True,
|
"requires_data_packages": True,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if s.FLAGS.get("PLUGINS", False):
|
if s.FLAGS.get("PLUGINS", False):
|
||||||
@ -1124,11 +1115,6 @@ def package_model(request, package_uuid, model_uuid):
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
# Sort data by prob desc
|
|
||||||
res["pred"] = sorted(
|
|
||||||
res["pred"], key=lambda x: x["probability"], reverse=True
|
|
||||||
)
|
|
||||||
|
|
||||||
return JsonResponse(res, safe=False)
|
return JsonResponse(res, safe=False)
|
||||||
|
|
||||||
elif half_life:
|
elif half_life:
|
||||||
@ -1232,7 +1218,9 @@ def package(request, package_uuid):
|
|||||||
if request.method == "GET":
|
if request.method == "GET":
|
||||||
if request.GET.get("export", False) == "true":
|
if request.GET.get("export", False) == "true":
|
||||||
filename = f"{current_package.get_name().replace(' ', '_')}_{current_package.uuid}.json"
|
filename = f"{current_package.get_name().replace(' ', '_')}_{current_package.uuid}.json"
|
||||||
pack_json = PackageManager.export_package(current_package)
|
pack_json = PackageManager.export_package(
|
||||||
|
current_package, include_models=False, include_external_identifiers=False
|
||||||
|
)
|
||||||
response = JsonResponse(pack_json, content_type="application/json")
|
response = JsonResponse(pack_json, content_type="application/json")
|
||||||
response["Content-Disposition"] = f'attachment; filename="{filename}"'
|
response["Content-Disposition"] = f'attachment; filename="{filename}"'
|
||||||
|
|
||||||
@ -1415,18 +1403,12 @@ def package_compounds(request, package_uuid):
|
|||||||
elif request.method == "POST":
|
elif request.method == "POST":
|
||||||
compound_name = request.POST.get("compound-name")
|
compound_name = request.POST.get("compound-name")
|
||||||
compound_smiles = request.POST.get("compound-smiles")
|
compound_smiles = request.POST.get("compound-smiles")
|
||||||
compound_molfile = request.POST.get("compound-molfile")
|
|
||||||
compound_description = request.POST.get("compound-description")
|
compound_description = request.POST.get("compound-description")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
c = Compound.create(
|
c = Compound.create(
|
||||||
current_package,
|
current_package, compound_smiles, compound_name, compound_description
|
||||||
compound_smiles,
|
|
||||||
molfile=compound_molfile,
|
|
||||||
name=compound_name,
|
|
||||||
description=compound_description,
|
|
||||||
)
|
)
|
||||||
except (InvalidSMILESException, InvalidMolfileException) as e:
|
except ValueError as e:
|
||||||
raise BadRequest(str(e))
|
raise BadRequest(str(e))
|
||||||
|
|
||||||
return redirect(c.url)
|
return redirect(c.url)
|
||||||
@ -1552,15 +1534,11 @@ def package_compound_structures(request, package_uuid, compound_uuid):
|
|||||||
elif request.method == "POST":
|
elif request.method == "POST":
|
||||||
structure_name = request.POST.get("structure-name")
|
structure_name = request.POST.get("structure-name")
|
||||||
structure_smiles = request.POST.get("structure-smiles")
|
structure_smiles = request.POST.get("structure-smiles")
|
||||||
structure_molfile = request.POST.get("structure-molfile")
|
|
||||||
structure_description = request.POST.get("structure-description")
|
structure_description = request.POST.get("structure-description")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
cs = current_compound.add_structure(
|
cs = current_compound.add_structure(
|
||||||
structure_smiles,
|
structure_smiles, structure_name, structure_description
|
||||||
molfile=structure_molfile,
|
|
||||||
name=structure_name,
|
|
||||||
description=structure_description,
|
|
||||||
)
|
)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return error(
|
return error(
|
||||||
@ -1948,9 +1926,9 @@ def package_reactions(request, package_uuid):
|
|||||||
elif request.method == "POST":
|
elif request.method == "POST":
|
||||||
reaction_name = request.POST.get("reaction-name")
|
reaction_name = request.POST.get("reaction-name")
|
||||||
reaction_description = request.POST.get("reaction-description")
|
reaction_description = request.POST.get("reaction-description")
|
||||||
reaction_smiles = request.POST.get("reaction-smiles")
|
reactions_smirks = request.POST.get("reaction-smirks")
|
||||||
educts = reaction_smiles.split(">>")[0].split(".")
|
educts = reactions_smirks.split(">>")[0].split(".")
|
||||||
products = reaction_smiles.split(">>")[1].split(".")
|
products = reactions_smirks.split(">>")[1].split(".")
|
||||||
|
|
||||||
r = Reaction.create(
|
r = Reaction.create(
|
||||||
current_package,
|
current_package,
|
||||||
@ -2131,14 +2109,12 @@ def package_pathways(request, package_uuid):
|
|||||||
else:
|
else:
|
||||||
prediction_setting = current_user.prediction_settings()
|
prediction_setting = current_user.prediction_settings()
|
||||||
|
|
||||||
is_predict_mode = pw_mode in {"predict", "incremental"}
|
|
||||||
|
|
||||||
pw = Pathway.create(
|
pw = Pathway.create(
|
||||||
current_package,
|
current_package,
|
||||||
stand_smiles if is_predict_mode else smiles,
|
stand_smiles,
|
||||||
name=name,
|
name=name,
|
||||||
description=description,
|
description=description,
|
||||||
predicted=is_predict_mode,
|
predicted=pw_mode in {"predict", "incremental"},
|
||||||
)
|
)
|
||||||
|
|
||||||
# set mode
|
# set mode
|
||||||
@ -2379,17 +2355,8 @@ def package_pathway_nodes(request, package_uuid, pathway_uuid):
|
|||||||
node_name = request.POST.get("node-name")
|
node_name = request.POST.get("node-name")
|
||||||
node_description = request.POST.get("node-description")
|
node_description = request.POST.get("node-description")
|
||||||
|
|
||||||
node_smiles = request.POST.get("node-smiles")
|
node_smiles = request.POST.get("node-smiles").strip()
|
||||||
node_molfile = request.POST.get("node-molfile")
|
current_pathway.add_node(node_smiles, name=node_name, description=node_description)
|
||||||
|
|
||||||
try:
|
|
||||||
current_pathway.add_node(
|
|
||||||
node_smiles, molfile=node_molfile, name=node_name, description=node_description
|
|
||||||
)
|
|
||||||
except InvalidSMILESException:
|
|
||||||
return error(
|
|
||||||
request, "Node creation failed!", f"Given SMILES ({node_smiles}) is invalid"
|
|
||||||
)
|
|
||||||
|
|
||||||
return redirect(current_pathway.url)
|
return redirect(current_pathway.url)
|
||||||
|
|
||||||
@ -2497,26 +2464,7 @@ def package_pathway_node(request, package_uuid, pathway_uuid, node_uuid):
|
|||||||
|
|
||||||
return JsonResponse({"success": current_node.url})
|
return JsonResponse({"success": current_node.url})
|
||||||
|
|
||||||
new_node_name = request.POST.get("node-name")
|
return HttpResponseBadRequest()
|
||||||
new_node_description = request.POST.get("node-description")
|
|
||||||
|
|
||||||
if any([new_node_name, new_node_description]):
|
|
||||||
if new_node_name is not None and new_node_name.strip() != "":
|
|
||||||
new_node_name = nh3.clean(new_node_name.strip(), tags=s.ALLOWED_HTML_TAGS).strip()
|
|
||||||
current_node.name = new_node_name
|
|
||||||
|
|
||||||
if new_node_description is not None and new_node_description.strip() != "":
|
|
||||||
new_node_description = nh3.clean(
|
|
||||||
new_node_description.strip(), tags=s.ALLOWED_HTML_TAGS
|
|
||||||
).strip()
|
|
||||||
current_node.description = new_node_description
|
|
||||||
|
|
||||||
current_node.save()
|
|
||||||
|
|
||||||
return redirect(current_node.url)
|
|
||||||
|
|
||||||
return error(request, "Node update failed!", "No changes were made to the node")
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return HttpResponseNotAllowed(["GET", "POST"])
|
return HttpResponseNotAllowed(["GET", "POST"])
|
||||||
|
|
||||||
@ -2586,9 +2534,6 @@ def package_pathway_edges(request, package_uuid, pathway_uuid):
|
|||||||
substrate_nodes, product_nodes, name=edge_name, description=edge_description
|
substrate_nodes, product_nodes, name=edge_name, description=edge_description
|
||||||
)
|
)
|
||||||
|
|
||||||
# Update depths as sideeffect of above operation
|
|
||||||
current_pathway.update_depths()
|
|
||||||
|
|
||||||
return redirect(current_pathway.url)
|
return redirect(current_pathway.url)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
@ -3048,15 +2993,9 @@ def settings(request):
|
|||||||
new_default = request.POST.get("prediction-setting-new-default", "off") == "on"
|
new_default = request.POST.get("prediction-setting-new-default", "off") == "on"
|
||||||
|
|
||||||
# min 2, max s.DEFAULT_MAX_NUMBER_OF_NODES
|
# min 2, max s.DEFAULT_MAX_NUMBER_OF_NODES
|
||||||
temp_max_nodes = request.POST.get("prediction-setting-max-nodes")
|
|
||||||
if temp_max_nodes is None or temp_max_nodes == "" or int(temp_max_nodes) == -1:
|
|
||||||
temp_max_nodes = s.DEFAULT_MAX_NUMBER_OF_NODES
|
|
||||||
else:
|
|
||||||
temp_max_nodes = int(request.POST.get("prediction-setting-max-nodes", 1))
|
|
||||||
|
|
||||||
max_nodes = min(
|
max_nodes = min(
|
||||||
max(
|
max(
|
||||||
temp_max_nodes,
|
int(request.POST.get("prediction-setting-max-nodes", 1)),
|
||||||
2,
|
2,
|
||||||
),
|
),
|
||||||
s.DEFAULT_MAX_NUMBER_OF_NODES,
|
s.DEFAULT_MAX_NUMBER_OF_NODES,
|
||||||
@ -3077,7 +3016,6 @@ def settings(request):
|
|||||||
|
|
||||||
model_uuid = model_url.split("/")[-1]
|
model_uuid = model_url.split("/")[-1]
|
||||||
params["model"] = EPModel.objects.get(uuid=model_uuid)
|
params["model"] = EPModel.objects.get(uuid=model_uuid)
|
||||||
# TODO Check if removed if request contains "" or not at all
|
|
||||||
params["model_threshold"] = request.POST.get(
|
params["model_threshold"] = request.POST.get(
|
||||||
"model-based-prediction-setting-threshold", s.DEFAULT_MODEL_THRESHOLD
|
"model-based-prediction-setting-threshold", s.DEFAULT_MODEL_THRESHOLD
|
||||||
)
|
)
|
||||||
@ -3167,21 +3105,12 @@ def jobs(request):
|
|||||||
{"Home": s.SERVER_URL},
|
{"Home": s.SERVER_URL},
|
||||||
{"Jobs": s.SERVER_URL + "/jobs"},
|
{"Jobs": s.SERVER_URL + "/jobs"},
|
||||||
]
|
]
|
||||||
# if current_user.is_superuser:
|
if current_user.is_superuser:
|
||||||
# context["jobs"] = JobLog.objects.all().order_by("-created")
|
context["jobs"] = JobLog.objects.all().order_by("-created")
|
||||||
# else:
|
else:
|
||||||
# context["jobs"] = JobLog.objects.filter(user=current_user).order_by("-created")
|
context["jobs"] = JobLog.objects.filter(user=current_user).order_by("-created")
|
||||||
|
|
||||||
# Context for paginated template
|
return render(request, "collections/joblog.html", context)
|
||||||
context["entity_type"] = "joblog"
|
|
||||||
context["api_endpoint"] = f"{s.SERVER_PATH}/api/v1/joblog/"
|
|
||||||
context["per_page"] = s.API_PAGINATION_DEFAULT_PAGE_SIZE
|
|
||||||
context["list_title"] = "joblog"
|
|
||||||
context["list_mode"] = "combined"
|
|
||||||
|
|
||||||
return render(request, "collections/joblog_paginated.html", context)
|
|
||||||
|
|
||||||
# return render(request, "collections/joblog.html", context)
|
|
||||||
|
|
||||||
elif request.method == "POST":
|
elif request.method == "POST":
|
||||||
job_name = request.POST.get("job-name")
|
job_name = request.POST.get("job-name")
|
||||||
|
|||||||
1
fixtures/Fixture_Package.json
Normal file
@ -65,25 +65,6 @@ def run_both_engines(SMILES, SMIRKS):
|
|||||||
|
|
||||||
|
|
||||||
def migration(request):
|
def migration(request):
|
||||||
accepted_diffs = [
|
|
||||||
"bt0055-3469.1",
|
|
||||||
"bt0056-2685",
|
|
||||||
"bt0193-4263",
|
|
||||||
"bt0231-1871.1",
|
|
||||||
"bt0242-3803",
|
|
||||||
"bt0254-4224.1",
|
|
||||||
"bt0254-4224.2",
|
|
||||||
"bt0291-1129",
|
|
||||||
"bt0337-3543",
|
|
||||||
"bt0391-4285",
|
|
||||||
"bt0402-3576",
|
|
||||||
"bt0404-3928",
|
|
||||||
"bt0416-4269",
|
|
||||||
"bt0432-4254",
|
|
||||||
"bt0337-4117",
|
|
||||||
"bt0322-3393",
|
|
||||||
]
|
|
||||||
|
|
||||||
if request.method == "GET":
|
if request.method == "GET":
|
||||||
context = get_base_context(request)
|
context = get_base_context(request)
|
||||||
|
|
||||||
@ -128,11 +109,11 @@ def migration(request):
|
|||||||
),
|
),
|
||||||
"id": str(r.uuid),
|
"id": str(r.uuid),
|
||||||
"url": r.url,
|
"url": r.url,
|
||||||
"status": res or r.name in accepted_diffs,
|
"status": res,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
if res or r.name in accepted_diffs:
|
if res:
|
||||||
success += 1
|
success += 1
|
||||||
else:
|
else:
|
||||||
error += 1
|
error += 1
|
||||||
@ -154,16 +135,7 @@ def migration(request):
|
|||||||
|
|
||||||
for r in migration_status["results"]:
|
for r in migration_status["results"]:
|
||||||
r["detail_url"] = r["detail_url"].replace("http://localhost:8000", s.SERVER_URL)
|
r["detail_url"] = r["detail_url"].replace("http://localhost:8000", s.SERVER_URL)
|
||||||
if r["name"] in accepted_diffs:
|
|
||||||
r["status"] = True
|
|
||||||
|
|
||||||
migration_status["results"] = sorted(
|
|
||||||
migration_status["results"], key=lambda x: (x["status"], x["name"])
|
|
||||||
)
|
|
||||||
|
|
||||||
num_success = sum([int(x["status"]) for x in migration_status["results"]])
|
|
||||||
migration_status["success"] = num_success
|
|
||||||
migration_status["error"] = migration_status["total"] - num_success
|
|
||||||
context.update(**migration_status)
|
context.update(**migration_status)
|
||||||
|
|
||||||
return render(request, "migration.html", context)
|
return render(request, "migration.html", context)
|
||||||
|
|||||||
@ -21,11 +21,5 @@
|
|||||||
"django",
|
"django",
|
||||||
"tailwindcss",
|
"tailwindcss",
|
||||||
"daisyui"
|
"daisyui"
|
||||||
],
|
|
||||||
"pnpm": {
|
|
||||||
"onlyBuiltDependencies": [
|
|
||||||
"@parcel/watcher",
|
|
||||||
"@tailwindcss/oxide"
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|||||||
@ -46,7 +46,7 @@ class PepperPrediction(PropertyPrediction):
|
|||||||
|
|
||||||
import matplotlib.patches as mpatches
|
import matplotlib.patches as mpatches
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from matplotlib.figure import Figure
|
from matplotlib import pyplot as plt
|
||||||
from scipy import stats
|
from scipy import stats
|
||||||
|
|
||||||
"""
|
"""
|
||||||
@ -101,8 +101,7 @@ class PepperPrediction(PropertyPrediction):
|
|||||||
mask_red = x > vp
|
mask_red = x > vp
|
||||||
|
|
||||||
# Plot
|
# Plot
|
||||||
fig = Figure(figsize=(9, 5.5))
|
fig, ax = plt.subplots(figsize=(9, 5.5))
|
||||||
ax = fig.subplots()
|
|
||||||
ax.plot(x, y, color="#1f4e79", lw=2, label="Lognormal PDF")
|
ax.plot(x, y, color="#1f4e79", lw=2, label="Lognormal PDF")
|
||||||
|
|
||||||
if np.any(mask_green):
|
if np.any(mask_green):
|
||||||
@ -147,12 +146,13 @@ class PepperPrediction(PropertyPrediction):
|
|||||||
]
|
]
|
||||||
ax.legend(handles=patches, frameon=True)
|
ax.legend(handles=patches, frameon=True)
|
||||||
|
|
||||||
fig.tight_layout()
|
plt.tight_layout()
|
||||||
|
|
||||||
# --- Export to SVG string ---
|
# --- Export to SVG string ---
|
||||||
buf = io.StringIO()
|
buf = io.StringIO()
|
||||||
fig.savefig(buf, format="svg", bbox_inches="tight")
|
fig.savefig(buf, format="svg", bbox_inches="tight")
|
||||||
svg = buf.getvalue()
|
svg = buf.getvalue()
|
||||||
|
plt.close(fig)
|
||||||
buf.close()
|
buf.close()
|
||||||
|
|
||||||
return svg
|
return svg
|
||||||
|
|||||||
@ -187,9 +187,8 @@ class Pepper:
|
|||||||
groups = [group for group in dataset.group_by("structure_id")]
|
groups = [group for group in dataset.group_by("structure_id")]
|
||||||
|
|
||||||
# Unless explicitly set compute everything serial
|
# Unless explicitly set compute everything serial
|
||||||
n_threads = int(os.environ.get("N_PEPPER_THREADS", 1))
|
if os.environ.get("N_PEPPER_THREADS", 1) > 1:
|
||||||
if n_threads > 1:
|
results = Parallel(n_jobs=os.environ["N_PEPPER_THREADS"])(
|
||||||
results = Parallel(n_jobs=n_threads)(
|
|
||||||
delayed(compute_bayes_per_group)(group[1])
|
delayed(compute_bayes_per_group)(group[1])
|
||||||
for group in dataset.group_by("structure_id")
|
for group in dataset.group_by("structure_id")
|
||||||
)
|
)
|
||||||
|
|||||||
@ -1,5 +1,3 @@
|
|||||||
allowBuilds:
|
|
||||||
'@parcel/watcher': true
|
|
||||||
onlyBuiltDependencies:
|
onlyBuiltDependencies:
|
||||||
- '@parcel/watcher'
|
- '@parcel/watcher'
|
||||||
- '@tailwindcss/oxide'
|
- '@tailwindcss/oxide'
|
||||||
@ -34,12 +34,3 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@import "./daisyui-theme.css";
|
@import "./daisyui-theme.css";
|
||||||
|
|
||||||
select.select[multiple] {
|
|
||||||
display: block;
|
|
||||||
white-space: normal;
|
|
||||||
}
|
|
||||||
|
|
||||||
p a {
|
|
||||||
@apply underline;
|
|
||||||
}
|
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 1.5 KiB |
@ -1,30 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
|
||||||
viewBox="0 0 76 76" style="enable-background:new 0 0 76 76;" xml:space="preserve">
|
|
||||||
<style type="text/css">
|
|
||||||
.st0{fill:#10384F;}
|
|
||||||
.st1{fill:#89D329;}
|
|
||||||
.st2{fill:#00BCFF;}
|
|
||||||
</style>
|
|
||||||
<g id="Bayer_Cross_1_">
|
|
||||||
<path class="st0" d="M35.9,11.3h4.4c0.5,0,0.9-0.4,0.9-0.9c0-0.5-0.4-0.9-0.9-0.9h-4.4V11.3z M35.9,15.5h4.5c0.6,0,1-0.4,1-1
|
|
||||||
c0-0.6-0.4-1-1-1h-4.5V15.5z M43,12.3c0.6,0.6,1,1.4,1,2.3c0,1.8-1.4,3.2-3.2,3.2h-7.3V7.3l7.2,0c1.7,0,3.1,1.4,3.1,3.1
|
|
||||||
C43.7,11.1,43.4,11.8,43,12.3z M44.7,30.3H42l-0.8-1.8h-5.9l-0.8,1.8h-2.7L37,19.8h2.4L44.7,30.3z M38.2,22.5l-1.8,3.8H40
|
|
||||||
L38.2,22.5z M41.8,32.6h3l-5.3,6.8v3.7h-2.5v-3.7l-5.3-6.8h3l3.6,4.8L41.8,32.6z M55.7,32.6v2.3h-7v1.8l6.8,0v2.3h-6.8v2h7v2.3
|
|
||||||
h-9.5V32.6H55.7z M63.4,39.1h-1.9v4h-2.5V32.6h6.4c1.8,0,3.2,1.5,3.2,3.3c0,1.5-1,2.7-2.3,3.1l3.1,4.1h-3L63.4,39.1z M65.2,34.8
|
|
||||||
h-3.6v2h3.6c0.6,0,1-0.5,1-1C66.2,35.3,65.7,34.8,65.2,34.8z M32.8,43.1h-2.7l-0.8-1.8h-5.9l-0.8,1.8h-2.7l5.3-10.5h2.4L32.8,43.1z
|
|
||||||
M26.3,35.3l-1.8,3.8h3.7L26.3,35.3z M10.4,36.6h4.4c0.5,0,0.9-0.4,0.9-0.9c0-0.5-0.4-0.9-0.9-0.9l-4.4,0V36.6z M10.4,40.8h4.5
|
|
||||||
c0.6,0,1-0.4,1-1c0-0.6-0.4-1-1-1h-4.5V40.8z M17.5,37.6c0.6,0.6,1,1.4,1,2.3c0,1.8-1.4,3.2-3.2,3.2H7.9V32.6h7.2
|
|
||||||
c1.7,0,3.1,1.4,3.1,3.1C18.2,36.4,17.9,37.1,17.5,37.6z M43,45.3v2.3h-7v1.8l6.8,0v2.3h-6.8v2h7v2.3h-9.5V45.3H43z M41.2,61.6
|
|
||||||
c0-0.6-0.4-1-1-1h-4.3v2h4.3C40.8,62.6,41.2,62.2,41.2,61.6z M33.4,68.9V58.4h7c1.8,0,3.2,1.5,3.2,3.3c0,1.4-0.8,2.5-2,3l3.2,4.2
|
|
||||||
h-3l-3-4h-2.9v4H33.4z"/>
|
|
||||||
<path class="st1" d="M76.1,35.6C74.9,15.8,58.4,0,38.2,0C18,0,1.5,15.8,0.3,35.6c0,0.8,0.1,1.6,0.2,2.4c0.8,6.6,3.3,12.7,7.1,17.8
|
|
||||||
c6.9,9.4,18,15.5,30.6,15.5c-17.6,0-32-13.7-33.2-30.9c-0.1-0.8-0.1-1.6-0.1-2.4c0-0.8,0-1.6,0.1-2.4C6.2,18.4,20.6,4.7,38.2,4.7
|
|
||||||
c12.6,0,23.7,6.1,30.6,15.5c3.8,5.1,6.3,11.2,7.1,17.8c0.1,0.8,0.2,1.6,0.2,2.3c0-0.8,0.1-1.6,0.1-2.4
|
|
||||||
C76.2,37.2,76.2,36.4,76.1,35.6"/>
|
|
||||||
<path class="st2" d="M0.3,40.4C1.5,60.2,18,76,38.2,76c20.2,0,36.7-15.8,37.9-35.6c0-0.8-0.1-1.6-0.2-2.4
|
|
||||||
c-0.8-6.6-3.3-12.7-7.1-17.8c-6.9-9.4-18-15.5-30.6-15.5c17.6,0,32,13.7,33.2,30.9c0.1,0.8,0.1,1.6,0.1,2.4c0,0.8,0,1.6-0.1,2.4
|
|
||||||
c-1.2,17.3-15.6,30.9-33.2,30.9c-12.6,0-23.7-6.1-30.6-15.5C3.8,50.7,1.3,44.6,0.5,38c-0.1-0.8-0.2-1.6-0.2-2.3
|
|
||||||
c0,0.8-0.1,1.6-0.1,2.4C0.2,38.8,0.2,39.6,0.3,40.4"/>
|
|
||||||
</g>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 3.2 KiB |
@ -59,9 +59,6 @@ document.addEventListener("alpine:init", () => {
|
|||||||
get isEditMode() {
|
get isEditMode() {
|
||||||
return this.mode === "edit";
|
return this.mode === "edit";
|
||||||
},
|
},
|
||||||
get isRequired() {
|
|
||||||
return (this.schema.required || []).indexOf(this.fieldName) > -1
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Text widget
|
// Text widget
|
||||||
@ -296,34 +293,6 @@ document.addEventListener("alpine:init", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
// PubMed link widget
|
|
||||||
Alpine.data(
|
|
||||||
"doiWidget",
|
|
||||||
(fieldName, data, schema, uiSchema, mode, debugErrors, context = null) => ({
|
|
||||||
...baseWidget(
|
|
||||||
fieldName,
|
|
||||||
data,
|
|
||||||
schema,
|
|
||||||
uiSchema,
|
|
||||||
mode,
|
|
||||||
debugErrors,
|
|
||||||
context,
|
|
||||||
),
|
|
||||||
|
|
||||||
get value() {
|
|
||||||
return this.data[this.fieldName] || "";
|
|
||||||
},
|
|
||||||
set value(v) {
|
|
||||||
this.data[this.fieldName] = v;
|
|
||||||
},
|
|
||||||
get doiUrl() {
|
|
||||||
return this.value
|
|
||||||
? `https://dx.doi.org/${this.value}`
|
|
||||||
: null;
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Compound link widget
|
// Compound link widget
|
||||||
Alpine.data(
|
Alpine.data(
|
||||||
"compoundWidget",
|
"compoundWidget",
|
||||||
|
|||||||
@ -5,126 +5,6 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
document.addEventListener('alpine:init', () => {
|
document.addEventListener('alpine:init', () => {
|
||||||
|
|
||||||
const basePagination = (
|
|
||||||
items,
|
|
||||||
currentPage,
|
|
||||||
totalPages,
|
|
||||||
totalItems,
|
|
||||||
perPage,
|
|
||||||
isReviewed,
|
|
||||||
instanceId
|
|
||||||
) => ({
|
|
||||||
items,
|
|
||||||
currentPage,
|
|
||||||
totalPages,
|
|
||||||
totalItems,
|
|
||||||
perPage,
|
|
||||||
isReviewed,
|
|
||||||
instanceId,
|
|
||||||
|
|
||||||
get paginatedItems() {
|
|
||||||
return this.items;
|
|
||||||
},
|
|
||||||
|
|
||||||
get showingStart() {
|
|
||||||
if (this.totalItems === 0) return 0;
|
|
||||||
return (this.currentPage - 1) * this.perPage + 1;
|
|
||||||
},
|
|
||||||
|
|
||||||
get showingEnd() {
|
|
||||||
if (this.totalItems === 0) return 0;
|
|
||||||
return Math.min((this.currentPage - 1) * this.perPage + this.items.length, this.totalItems);
|
|
||||||
},
|
|
||||||
|
|
||||||
nextPage() {
|
|
||||||
if (this.currentPage < this.totalPages) {
|
|
||||||
this.fetchPage(this.currentPage + 1);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
prevPage() {
|
|
||||||
if (this.currentPage > 1) {
|
|
||||||
this.fetchPage(this.currentPage - 1);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
goToPage(page) {
|
|
||||||
if (page >= 1 && page <= this.totalPages) {
|
|
||||||
this.fetchPage(page);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
get pageNumbers() {
|
|
||||||
const pages = [];
|
|
||||||
const total = this.totalPages;
|
|
||||||
const current = this.currentPage;
|
|
||||||
|
|
||||||
if (total === 0) {
|
|
||||||
return pages;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (total <= 7) {
|
|
||||||
for (let i = 1; i <= total; i++) {
|
|
||||||
pages.push({ page: i, isEllipsis: false, key: `${this.instanceId}-page-${i}` });
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
pages.push({ page: 1, isEllipsis: false, key: `${this.instanceId}-page-1` });
|
|
||||||
|
|
||||||
let rangeStart;
|
|
||||||
let rangeEnd;
|
|
||||||
|
|
||||||
if (current <= 4) {
|
|
||||||
rangeStart = 2;
|
|
||||||
rangeEnd = 5;
|
|
||||||
} else if (current >= total - 3) {
|
|
||||||
rangeStart = total - 4;
|
|
||||||
rangeEnd = total - 1;
|
|
||||||
} else {
|
|
||||||
rangeStart = current - 1;
|
|
||||||
rangeEnd = current + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rangeStart > 2) {
|
|
||||||
pages.push({ page: '...', isEllipsis: true, key: `${this.instanceId}-ellipsis-start` });
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = rangeStart; i <= rangeEnd; i++) {
|
|
||||||
pages.push({ page: i, isEllipsis: false, key: `${this.instanceId}-page-${i}` });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rangeEnd < total - 1) {
|
|
||||||
pages.push({ page: '...', isEllipsis: true, key: `${this.instanceId}-ellipsis-end` });
|
|
||||||
}
|
|
||||||
|
|
||||||
pages.push({ page: total, isEllipsis: false, key: `${this.instanceId}-page-${total}` });
|
|
||||||
}
|
|
||||||
|
|
||||||
return pages;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Alpine.data('paginatedList',
|
|
||||||
(items, options = {}) => ({
|
|
||||||
...basePagination(items,1, 0, 0, options.perPage || 50, options.isReviewed || false, options.instanceId || Math.random().toString(36).substring(2, 9),),
|
|
||||||
|
|
||||||
init() {
|
|
||||||
this.fetchPage(1);
|
|
||||||
},
|
|
||||||
|
|
||||||
async fetchPage(page) {
|
|
||||||
this.totalItems = this.items.length;
|
|
||||||
this.totalPages = Math.ceil(this.items.length / this.perPage);
|
|
||||||
this.currentPage = page
|
|
||||||
|
|
||||||
const start = page * this.perPage - this.perPage;
|
|
||||||
const end = page * this.perPage;
|
|
||||||
return this.items.slice(start, end);
|
|
||||||
}
|
|
||||||
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
Alpine.data('remotePaginatedList', (options = {}) => ({
|
Alpine.data('remotePaginatedList', (options = {}) => ({
|
||||||
items: [],
|
items: [],
|
||||||
currentPage: 1,
|
currentPage: 1,
|
||||||
|
|||||||
57
static/js/ketcher2/DEVNOTES.md
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
Stable [Node.js](https://nodejs.org) version
|
||||||
|
|
||||||
|
## Build instructions
|
||||||
|
|
||||||
|
npm install
|
||||||
|
npm start
|
||||||
|
|
||||||
|
For production build:
|
||||||
|
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
You could also build only the style with command
|
||||||
|
|
||||||
|
npm run style
|
||||||
|
|
||||||
|
## Indigo Service
|
||||||
|
|
||||||
|
Ketcher uses Indigo Service for server operations.
|
||||||
|
You can use `--api-path` parameter to start with it:
|
||||||
|
|
||||||
|
npm start -- --api-path=<server-url>
|
||||||
|
For production build:
|
||||||
|
|
||||||
|
npm run build -- --api-path=<server-url>
|
||||||
|
|
||||||
|
You can find the instruction for service installation
|
||||||
|
[here](http://lifescience.opensource.epam.com/indigo/service/index.html).
|
||||||
|
|
||||||
|
## Tests instructions
|
||||||
|
|
||||||
|
You can start tests for input/output `.mol`-files and render.
|
||||||
|
|
||||||
|
npm test
|
||||||
|
|
||||||
|
Tests are started for all structures in `test/fixtures` directory.
|
||||||
|
|
||||||
|
To start the tests separately:
|
||||||
|
|
||||||
|
npm run test-io
|
||||||
|
npm run test-render
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
|
||||||
|
You can use following parameters to start the tests:
|
||||||
|
- `--fixtures` - for the choice of a specific directory with molecules
|
||||||
|
- `--headless` - for start of the browser in headless mode
|
||||||
|
|
||||||
|
```
|
||||||
|
npm run test-render -- --fixtures=fixtures/super --headless
|
||||||
|
```
|
||||||
|
|
||||||
|
If you have added new structures for testing to the `test/fixtures` directory
|
||||||
|
you have to generate `svg` from them for correct render-test with:
|
||||||
|
|
||||||
|
npm run generate-svg
|
||||||
184
static/js/ketcher2/LICENSE
Normal file
@ -0,0 +1,184 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright 2017 EPAM Systems
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
5
static/js/ketcher2/LICENSE-history
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
Ketcher version 1 was released under GNU Affero General Public License v3.0
|
||||||
|
Ketcher version 2 was re-licensed under Apache License, Version 2.
|
||||||
|
|
||||||
|
Current version is distributed by the terms of the Apache License, Version 2.
|
||||||
|
which is included in the file LICENSE, found at the root of the Ketcher source tree.
|
||||||
19
static/js/ketcher2/NOTICE
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
Ketcher
|
||||||
|
Copyright (C) 2017 EPAM Systems
|
||||||
|
This product includes software developed at EPAM Systems, Inc.
|
||||||
|
|
||||||
|
In addition, this product contains dependencies on files licensed under:
|
||||||
|
|
||||||
|
The FreeBSD Documentation License https://www.freebsd.org/copyright/freebsd-doc-license.html
|
||||||
|
The MIT License https://opensource.org/licenses/MIT
|
||||||
|
X11 License http://www.xfree86.org/3.3.6/COPYRIGHT2.html
|
||||||
|
Academic Free License https://opensource.org/licenses/AFL-3.0
|
||||||
|
Apache License, Version 1.0 http://www.apache.org/licenses/LICENSE-1.0
|
||||||
|
Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
The 2-Clause BSD License https://opensource.org/licenses/BSD-2-Clause
|
||||||
|
The 3-Clause BSD License https://opensource.org/licenses/BSD-3-Clause
|
||||||
|
ISC License (ISC) https://opensource.org/licenses/ISC
|
||||||
|
GNU Lesser General Public License version 2.1 https://opensource.org/licenses/LGPL-2.1
|
||||||
|
The Mozilla Public License https://opensource.org/licenses/MPL-1.0
|
||||||
|
Public Domain https://wiki.creativecommons.org/wiki/Public_domain
|
||||||
|
Unlicense http://unlicense.org/
|
||||||
35
static/js/ketcher2/README.md
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
# EPAM Ketcher projects
|
||||||
|
Copyright (c) 2017 EPAM Systems, Inc
|
||||||
|
|
||||||
|
Ketcher is an open-source web-based chemical structure editor incorporating high performance, good portability, light weight, and ability to easily integrate into a custom web-application. Ketcher is designed for chemists, laboratory scientists and technicians who draw structures and reactions.
|
||||||
|
|
||||||
|
## KEY FEATURES
|
||||||
|
* Fast 2D structure representation that satisfies common chemical drawing standards
|
||||||
|
* 3D structure visualization
|
||||||
|
* Draw and edit structures using major tools: Atom Tool, Bond Tool, and Template Tool
|
||||||
|
* Template library (including custom and user's templates)
|
||||||
|
* Add atom and bond basic properties and query features, add aliases and Generic groups
|
||||||
|
* Select, modify, and erase connected and unconnected atoms and bonds using Selection Tool, or using Shift key
|
||||||
|
* Simple Structure Clean up Tool (checks bonds length, angles and spatial arrangement of atoms) and Advanced Structure Clean up Tool (+ stereochemistry checking and structure layout)
|
||||||
|
* Aromatize/De-aromatize Tool
|
||||||
|
* Calculate CIP Descriptors Tool
|
||||||
|
* Structure Check Tool
|
||||||
|
* MW and Structure Parameters Calculate Tool
|
||||||
|
* Stereochemistry support during editing, loading, and saving chemical structures
|
||||||
|
* Storing history of actions, with the ability to rollback to previous state
|
||||||
|
* Ability to load and save structures and reactions in MDL Molfile or RXN file format, InChI String, ChemAxon Extended SMILES, ChemAxon Extended CML file formats
|
||||||
|
* Easy to use R-Group and S-Group tools (Generic, Multiple group, SRU polymer, peratom, Data S-Group)
|
||||||
|
* Reaction Tool (reaction generating, manual and automatic atom-to-atom mapping)
|
||||||
|
* Flip/Rotate Tool
|
||||||
|
* Zoom in/out, hotkeys, cut/copy/paste
|
||||||
|
* OCR - ability to recognize structures at pictures (image files) and reproduce them
|
||||||
|
* Copy and paste between different chemical editors
|
||||||
|
* Settings support (Rendering, Displaying, Debugging)
|
||||||
|
* Use of SVG to achieve best quality in-browser chemical structure rendering
|
||||||
|
* Languages: JavaScript with third-party libraries
|
||||||
|
|
||||||
|
## Build instructions
|
||||||
|
Please read [DEVNOTES.md](DEVNOTES.md) for details.
|
||||||
|
|
||||||
|
## License
|
||||||
|
Please read [LICENSE](LICENSE) and [NOTICE](NOTICE) for details.
|
||||||
BIN
static/js/ketcher2/doc/analyse.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
static/js/ketcher2/doc/atom-dialog.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
static/js/ketcher2/doc/attpoints-dialog.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
static/js/ketcher2/doc/bond-dialog.png
Normal file
|
After Width: | Height: | Size: 15 KiB |
BIN
static/js/ketcher2/doc/bond-types.png
Normal file
|
After Width: | Height: | Size: 1014 B |
BIN
static/js/ketcher2/doc/bond.png
Normal file
|
After Width: | Height: | Size: 630 B |
BIN
static/js/ketcher2/doc/bonds.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
static/js/ketcher2/doc/chain.png
Normal file
|
After Width: | Height: | Size: 430 B |
BIN
static/js/ketcher2/doc/charge.png
Normal file
|
After Width: | Height: | Size: 1.3 KiB |
BIN
static/js/ketcher2/doc/check.png
Normal file
|
After Width: | Height: | Size: 45 KiB |
BIN
static/js/ketcher2/doc/collapsed.png
Normal file
|
After Width: | Height: | Size: 5.6 KiB |
BIN
static/js/ketcher2/doc/expanded.png
Normal file
|
After Width: | Height: | Size: 3.3 KiB |
BIN
static/js/ketcher2/doc/generic-groups.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
570
static/js/ketcher2/doc/help.md
Normal file
@ -0,0 +1,570 @@
|
|||||||
|
**Ketcher** is a tool to draw molecular structures and chemical
|
||||||
|
reactions.
|
||||||
|
|
||||||
|
# Ketcher Overview
|
||||||
|
|
||||||
|
**Ketcher** is a tool to draw molecular structures and chemical
|
||||||
|
reactions. Ketcher operates in two modes, the Server mode with most
|
||||||
|
functions available and the client mode with limited functions
|
||||||
|
available.
|
||||||
|
|
||||||
|
**Ketcher** consists of the following elements:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
**Note** : Depending on the screen size, some tools on the _Tool
|
||||||
|
palette_ can be displayed in expanded or collapsed forms.
|
||||||
|
|
||||||
|
Using the _Tool palette_, you can
|
||||||
|
|
||||||
|
* draw and edit a molecule or reaction by clicking on and dragging
|
||||||
|
atoms, bonds, and other elements provided with the buttons on the
|
||||||
|
_Atoms_ toolbar and _Tool palette_;
|
||||||
|
|
||||||
|
* delete any element of the drawing (atom or bond) by clicking on it
|
||||||
|
with the Erase tool;
|
||||||
|
|
||||||
|
* delete the entire molecule or its fragment by a lasso,
|
||||||
|
rectangular, or fragment selection with the Erase tool;
|
||||||
|
|
||||||
|
* draw special structures (see the following sections);
|
||||||
|
|
||||||
|
* select the entire molecule or its fragment in one of the following
|
||||||
|
ways (click on the button to see the list of available options):
|
||||||
|
|
||||||
|
* in the expanded form
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* in the collapsed form
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
To select one atom or bond, click Lasso or Rectangle Selection tool,
|
||||||
|
and then click the atom or bond.
|
||||||
|
|
||||||
|
To select the entire structure:
|
||||||
|
|
||||||
|
* Select the Fragment Selection tool and then click the object.
|
||||||
|
|
||||||
|
* Select the Lasso or Rectangle Selection tool, and then drag the
|
||||||
|
mouse to select the object.
|
||||||
|
|
||||||
|
* `Ctrl-click` with the Lasso or Rectangle Selection tool.
|
||||||
|
|
||||||
|
To select multiple atoms, bonds, structures, or other objects, do one
|
||||||
|
of the following:
|
||||||
|
|
||||||
|
* `Shift-click` with the Lasso or Rectangle Selection tool selects
|
||||||
|
some (connected or not) atoms/bonds.
|
||||||
|
|
||||||
|
* With the Lasso or Rectangle Selection tool click and drag the
|
||||||
|
mouse around the atoms, bonds, or structures that you want to
|
||||||
|
select.
|
||||||
|
|
||||||
|
**Note** : `Ctrl+Shift-click` with the Lasso or Rectangle Selection tool
|
||||||
|
selects several structures.
|
||||||
|
|
||||||
|
You can use the buttons of the _Main_ toolbar:
|
||||||
|
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* **Clear Canvas** (1) button to start drawing a new molecule; this
|
||||||
|
command clears the drawing area;
|
||||||
|
|
||||||
|
* **Open…** (2) and **Save As…** (3) buttons to import a molecule
|
||||||
|
from a molecular file or save it to a supported molecular file
|
||||||
|
format;
|
||||||
|
|
||||||
|
* **Undo** / **Redo** (4), **Cut** (5), **Copy** (6), **Paste** (7),
|
||||||
|
**Zoom In** / **Out** (8), and **Scaling** (9) buttons to perform
|
||||||
|
the corresponding actions;
|
||||||
|
|
||||||
|
* **Layout** button (10) to change the position of the structure to
|
||||||
|
work with it with the most convenience;
|
||||||
|
|
||||||
|
* **Clean Up** button (11) to improve the appearance of the
|
||||||
|
structure by assigning them uniform bond lengths and angles.
|
||||||
|
|
||||||
|
* **Aromatize** / **Dearomatize** buttons (12) to mark aromatic
|
||||||
|
structures (to convert a structure to the Aromatic or Kekule
|
||||||
|
presentation);
|
||||||
|
|
||||||
|
* **Calculate CIP** button (13) to determine R/S and E/Z
|
||||||
|
configurations;
|
||||||
|
|
||||||
|
* **Check Structure** button (14) to check the following properties
|
||||||
|
of the structure:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* **Calculated Values** button (15) to display some properties of
|
||||||
|
the structure:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* **Recognize Molecule** button (16) to recognize a structure in the
|
||||||
|
image file and load it to the canvas;
|
||||||
|
|
||||||
|
* **3D Viewer** button (17) to open the structure in the
|
||||||
|
three-dimensional Viewer;
|
||||||
|
|
||||||
|
* **Settings** button (18) to make some settings for molecular
|
||||||
|
files:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* **Help** button (19) to view Help;
|
||||||
|
|
||||||
|
* **About** button (20) to display version and copyright information
|
||||||
|
of the program.
|
||||||
|
|
||||||
|
**Note** : **Layout,** **Clean Up,** **Aromatize** / **Dearomatize,**
|
||||||
|
**Calculate CIP,** **Check Structure,** **Calculated Values,**
|
||||||
|
**Recognize Molecule** and **3D View** buttons are active only in the
|
||||||
|
Server mode.
|
||||||
|
|
||||||
|
# 3D Viewer
|
||||||
|
|
||||||
|
The structure appears in a modal window after clicking on the **3D
|
||||||
|
Viewer** button:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
You can perform the following actions:
|
||||||
|
|
||||||
|
* Rotate the structure holding the left mouse button;
|
||||||
|
|
||||||
|
* Zoom In/Out the structure;
|
||||||
|
|
||||||
|
Ketcher Settings allow to change the appearance of the structure and background coloring.
|
||||||
|
|
||||||
|
"Lines" drawing method, "Bright" atom name coloring
|
||||||
|
method and "Light" background coloring are default.
|
||||||
|
|
||||||
|
# Drawing Atoms
|
||||||
|
|
||||||
|
To draw/edit atoms you can:
|
||||||
|
|
||||||
|
* select an atom in the Atoms toolbar and click inside the drawing
|
||||||
|
area;
|
||||||
|
|
||||||
|
* if the desired atom is absent in the toolbar, click on
|
||||||
|
the  button to invoke the Periodic Table and
|
||||||
|
click on the desired atom (available options: _Single_ – selection
|
||||||
|
of a single atom, _List_ – choose an atom from the list of selected
|
||||||
|
options (To allow one atom from a list of atoms of your choice at
|
||||||
|
that position), _Not List_ - exclude any atom on your list at that
|
||||||
|
position).
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* add an atom to the existing molecule by selecting an atom in the
|
||||||
|
_Atoms_ toolbar, clicking on an atom in the molecule, and dragging
|
||||||
|
the cursor; the atom will be added with a single bond; vacant
|
||||||
|
valences will be filled with the corresponding number of hydrogen
|
||||||
|
atoms;
|
||||||
|
|
||||||
|
* change an atom by selecting an atom in the _Atoms_ toolbar and
|
||||||
|
clicking on the atom to be changed; in the case a wrong valence thus
|
||||||
|
appears the atom will be underlined in red;
|
||||||
|
|
||||||
|
* change an atom by clicking on an existing atom with the
|
||||||
|
_Selection_ tool and waiting for a couple of seconds for the text
|
||||||
|
box to appear; type another atom symbol in the text box:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* change the charge of an atom by selecting the Charge Plus or
|
||||||
|
Charge Minus tool and clicking consecutively on an atom to
|
||||||
|
increase/decrease its charge
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* change an atom or its properties by double-clicking on the atom to
|
||||||
|
invoke the Atom Properties dialog (the dialog also provides atom
|
||||||
|
query features):
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* click on the Periodic Table button, open the Extended table and
|
||||||
|
select a corresponding Generic group or Special Node:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
# Drawing Bonds
|
||||||
|
|
||||||
|
To draw/edit bonds you can:
|
||||||
|
|
||||||
|
* Click an arrow on the Bond tool  in the Tools palette
|
||||||
|
to open the drop-down list with the following bond types:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
For the full screen format, the Bond tool from the Tools palette
|
||||||
|
splits into three: _Single Bond,__Single Up Bond,_ and _Any
|
||||||
|
Bond_,which include the corresponding bond types:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* select a bond type from the drop down list and click inside the
|
||||||
|
drawing area; a bond of the selected type will be drawn;
|
||||||
|
|
||||||
|
* click on an atom in the molecule; a bond of the selected type will
|
||||||
|
be added to the atom at the angle of 120 degrees;
|
||||||
|
|
||||||
|
* add a bond to the existing molecule by clicking on an atom in the
|
||||||
|
molecule and dragging the cursor; in this case you can set the angle
|
||||||
|
manually;
|
||||||
|
|
||||||
|
* change the bond type by clicking on it;
|
||||||
|
|
||||||
|
* use the Chain Tool  to draw consecutive single
|
||||||
|
bonds;
|
||||||
|
|
||||||
|
* change a bond or its properties by double-clicking on the bond to
|
||||||
|
invoke the Bond Properties dialog:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* clicking on a drawn stereo bond changes its direction.
|
||||||
|
|
||||||
|
* clicking with the Single Bond tool or Chain tool switches the bond type
|
||||||
|
cyclically: Single-Double-Triple-Single.
|
||||||
|
|
||||||
|
# Drawing R-Groups
|
||||||
|
|
||||||
|
Use the _R-Group_ toolbox  to draw R-groups in Markush
|
||||||
|
structures:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Selecting the _R-Group_ _Label_ Tool and clicking on an atom in the
|
||||||
|
structure invokes the dialog to select the R-Group label for a current
|
||||||
|
atom position in the structure:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Selecting the R-Group label and clicking **OK** converts the structure
|
||||||
|
into a Markush structure with the selected R-Group label:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
**Note** : You can choose several R-Group labels simultaneously:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Particular chemical fragments that may be substituted for a given
|
||||||
|
R-Group form a set of R-Group members. R-Group members can be any
|
||||||
|
structural fragment, including functional groups and single atoms or
|
||||||
|
atom lists.
|
||||||
|
|
||||||
|
To create a set of R-Group members:
|
||||||
|
|
||||||
|
1. Draw a structure to become an R-Group member.
|
||||||
|
|
||||||
|
2. Select the structure using the _R-Group Fragment Tool_ to invoke
|
||||||
|
the R-Group dialog; in this dialog select the label of the
|
||||||
|
R-Group to assign the fragment to.
|
||||||
|
|
||||||
|
3. Click on **OK** to convert the structure into an R-Group member.
|
||||||
|
|
||||||
|
An R-Group attachment point is the atom in an R-Group member fragment
|
||||||
|
that attaches the fragment to the initial Markush structure.
|
||||||
|
|
||||||
|
Selecting the _Attachment Point Tool_ and clicking on an atom in the
|
||||||
|
R-Group fragment converts this atom into an attachment point. If the
|
||||||
|
R-Group contains more than one attachment point, you can specify one
|
||||||
|
of them as primary and the other as secondary. You can select between
|
||||||
|
either the primary or secondary attachment point using the dialog that
|
||||||
|
appears after clicking on the atom:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
If there are two attachment points on an R-Group member, there must be
|
||||||
|
two corresponding attachments (bonds) to the R-Group atom that has the
|
||||||
|
same R-Group label. Clicking on **OK** in the above dialog creates the
|
||||||
|
attachment point.
|
||||||
|
|
||||||
|
Schematically, the entire process of the R-Group member creation can
|
||||||
|
be presented as:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
# R-Group Logic
|
||||||
|
|
||||||
|
**Ketcher** enables one to add logic when using R-Groups. To access
|
||||||
|
the R-Group logic:
|
||||||
|
|
||||||
|
1. Create an R-Group member fragment as described above.
|
||||||
|
|
||||||
|
2. Move the cursor over the entire fragment for the green frame to
|
||||||
|
appear, then click inside the fragment. The following dialog
|
||||||
|
appears:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
3. Specify **Occurrence** to define how many of an R-Group
|
||||||
|
occurs. If an R-Group atom appears several times in the initial
|
||||||
|
structure, you will specify **Occurrence**">n", n
|
||||||
|
being the number of occurrences; if it appears once, you see
|
||||||
|
"R1 > 0".
|
||||||
|
|
||||||
|
4. Specify H at **unoccupied** R-Group sites ( **RestH** ): check or
|
||||||
|
clear the checkbox.
|
||||||
|
|
||||||
|
5. Specify the logical **Condition**. Use the R-Group condition **If
|
||||||
|
R(i) Then** to specify whether the presence of an R-Group is
|
||||||
|
dependent on the presence of another R-Group.
|
||||||
|
|
||||||
|
|
||||||
|
# Marking S-Groups
|
||||||
|
|
||||||
|
To mark S-Groups, use the _S-Group tool_  and the
|
||||||
|
following dialog that appears after selecting a fragment with this
|
||||||
|
tool:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Available S-Group types:
|
||||||
|
|
||||||
|
_Generic_
|
||||||
|
|
||||||
|
Generic is a pair of brackets without any labels.
|
||||||
|
|
||||||
|
_Multiple group_
|
||||||
|
|
||||||
|
A Multiple group indicates a number of replications of a fragment or a part of a
|
||||||
|
structure in contracted form.
|
||||||
|
|
||||||
|
_SRU Polymer_
|
||||||
|
|
||||||
|
The Structural Repeating Unit (SRU) brackets enclose the structural
|
||||||
|
repeating of a polymer. You have three available patterns:
|
||||||
|
head-to-tail (the default), head-to-head, and either/unknown.
|
||||||
|
|
||||||
|
_Superatom_
|
||||||
|
|
||||||
|
An abbreviated structure (abbreviation) is all or part of a structure
|
||||||
|
(molecule or reaction component) that has been abbreviated to a text
|
||||||
|
label. Structures that you abbreviate keep their chemical
|
||||||
|
significance, but their underlying structure is hidden. The current
|
||||||
|
version can't display contracted structures but correctly
|
||||||
|
saves/reads them into/from files.
|
||||||
|
|
||||||
|
# Data S-Groups
|
||||||
|
|
||||||
|
The _Data S-Groups Tool_  is a separate tool for
|
||||||
|
comfortable use with the accustomed set of descriptors (like Attached
|
||||||
|
Data in **Marvin** Editor).
|
||||||
|
|
||||||
|
You can attach data to an atom, a fragment, a single bond, or a
|
||||||
|
group. The defined set of _Names_ and _Values_ is introduced for each
|
||||||
|
type of selected elements:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* Select the appropriate S-Group Field Name.
|
||||||
|
|
||||||
|
* Select or type the appropriate Field Value.
|
||||||
|
|
||||||
|
* Labels can be specified as Absolute, Relative or Attached.
|
||||||
|
|
||||||
|
# Changing Structure Display
|
||||||
|
|
||||||
|
Use the _Flip/Rotate_ tool  to change the structure
|
||||||
|
display:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
For the full screen format, the _Flip/Rotate_ tool is split into
|
||||||
|
separate buttons:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
_Rotate Tool_
|
||||||
|
|
||||||
|
This tool allows rotating objects.
|
||||||
|
* If some objects are selected, the tool rotates the selected objects.
|
||||||
|
* If no objects are selected, or all objects are selected, the tool rotates the whole canvas
|
||||||
|
* The default rotation step is 15 degrees.
|
||||||
|
* Press and hold the Ctrl key for more gradual continuous rotation with 1 degree rotation step
|
||||||
|
|
||||||
|
Select any bond on the structure and click Alt+H to rotate the structure so that the selected bond is placed horizontally.
|
||||||
|
Select any bond on the structure and click Alt+V to rotate the structure so that the selected bond is placed vertically.
|
||||||
|
|
||||||
|
_Flip Tool_
|
||||||
|
|
||||||
|
This tool flips the objects horizontally or vertically.
|
||||||
|
* If some objects are selected, the Horizontal Flip tool (or Alt+H) flips the selected objects horizontally
|
||||||
|
* If no objects are selected, or all objects are selected, the Horizontal Flip tool (or Alt+H) flips each structure horizontally
|
||||||
|
* If some objects are selected, the Vertical Flip tool (or Alt+V) flips the selected objects vertically
|
||||||
|
* If no objects are selected, or all objects are selected, the Vertical Flip tool (or Alt+V) flips each structure vertically
|
||||||
|
|
||||||
|
# Drawing Reactions
|
||||||
|
|
||||||
|
To draw/edit reactions you can
|
||||||
|
|
||||||
|
* draw reagents and products as described above;
|
||||||
|
* use options of the _Reaction Arrow Tool_  to draw an
|
||||||
|
arrow and pluses in the reaction equation and map same atoms in
|
||||||
|
reagents and products.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
**Note** : Reaction Auto-Mapping Tool is available only in the Server
|
||||||
|
mode.
|
||||||
|
|
||||||
|
# Templates toolbar
|
||||||
|
|
||||||
|
You can add templates (rings or other predefined structures) to the
|
||||||
|
structure using the _Templates_ toolbar together with the _Custom
|
||||||
|
Templates_ button located at the bottom:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
To add a ring to the molecule, select a ring from the toolbar and
|
||||||
|
click inside the drawing area, or click on an atom or a bond in the
|
||||||
|
molecule.
|
||||||
|
|
||||||
|
Rules of using templates:
|
||||||
|
|
||||||
|
* Selecting a template and clicking on an atom in the existing
|
||||||
|
structure adds the template to the structure connected with a single
|
||||||
|
bond:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* Selecting a template and dragging the cursor from an atom in the
|
||||||
|
existing structure adds the template directly to this atom resulting
|
||||||
|
in the fused structure:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* Dragging the cursor from an atom in the existing structure results
|
||||||
|
in the single bond attachment if the cursor is dragged to more than
|
||||||
|
the bond length; otherwise the fused structure is drawn.
|
||||||
|
* Selecting a template and clicking on a bond in the existing
|
||||||
|
structure created a bond-to-bond fused structure:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
* The bond in the initial structure is replaced with the bond in the
|
||||||
|
template.
|
||||||
|
|
||||||
|
* This procedure doesn't change the length of the bond in the
|
||||||
|
initial structure.
|
||||||
|
|
||||||
|
* Dragging the cursor relative to the initial bond applies the
|
||||||
|
template at the corresponding side of the bond.
|
||||||
|
|
||||||
|
**Note** : The added template will be fused by the default attachment
|
||||||
|
atom or bond preset in the program.
|
||||||
|
|
||||||
|
**Note** : User is able to define the attachment atom and bond by clicking
|
||||||
|
the Edit button for template structure.
|
||||||
|
|
||||||
|
|
||||||
|
The _Custom Templates_ button invokes the scrolling
|
||||||
|
list of templates available in the program; both built-in and created
|
||||||
|
by user:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
|
To create a user template:
|
||||||
|
* draw a structure.
|
||||||
|
* click the Save as button.
|
||||||
|
* click the Save to Templates button.
|
||||||
|
* enter a name and define the attachment atom and bond.
|
||||||
|
|
||||||
|
# Working with Files
|
||||||
|
|
||||||
|
Ketcher supports the following molecular formats that can be entered
|
||||||
|
either manually or from files:
|
||||||
|
|
||||||
|
* MDL Molfile or RXN file;
|
||||||
|
|
||||||
|
* Daylight SMILES (Server mode only);
|
||||||
|
|
||||||
|
* Daylight SMARTS (Server mode only);
|
||||||
|
|
||||||
|
* InChi string (Server mode only);
|
||||||
|
|
||||||
|
* CML file (Server mode only).
|
||||||
|
|
||||||
|
You can use the **Open…** and **Save As…** buttons of the _Main_
|
||||||
|
toolbar to import a molecule from a molecular file or save it to a
|
||||||
|
supported molecular file format. The _Open Structure_ dialog enables
|
||||||
|
one to either browse for a file (Server mode) or manually input, e.g.,
|
||||||
|
the Molfile ctable for the molecule to be imported:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
The _Save Structure_ dialog enables one to save the molecular file:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
**Note** : In the standalone version only mol/rxn are supported for
|
||||||
|
Open and mol/rxn/SMILES for Save.
|
||||||
|
|
||||||
|
|
||||||
|
# Hotkeys
|
||||||
|
|
||||||
|
You can use keyboard hotkeys (including Numeric keypad) for some
|
||||||
|
features/commands of the Editor. To display the hotkeys just place the
|
||||||
|
cursor over a toolbar button. If a hotkey is available for the button,
|
||||||
|
it will appear in brackets after the description of the button.
|
||||||
|
|
||||||
|
| Key | Action |
|
||||||
|
| --- | --- |
|
||||||
|
| `Esc` | Switching between the Lasso/Rectangle/Fragment Selection tools |
|
||||||
|
| `Del` | Delete the selected objects |
|
||||||
|
| `0` | Draw Any bond. |
|
||||||
|
| `1` | Single / Single Up / Single Down / Single Up/Down bond. Consecutive pressing switches between these types. |
|
||||||
|
| `2` | Double / Double Cis/Trans bond |
|
||||||
|
| `3` | Draw a triple bond. |
|
||||||
|
| `4` | Draw an aromatic bond. |
|
||||||
|
| `5` | Charge Plus/Charge Minus |
|
||||||
|
| `A` | Draw any atom |
|
||||||
|
| `H` | Draw a hydrogen |
|
||||||
|
| `C` | Draw a carbon |
|
||||||
|
| `N` | Draw a nitrogen |
|
||||||
|
| `O` | Draw an oxygen |
|
||||||
|
| `S` | Draw a sulfur |
|
||||||
|
| `F` | Draw a fluorine |
|
||||||
|
| `P` | Draw a phosphorus |
|
||||||
|
| `I` | Draw an iodine |
|
||||||
|
| `T` | Basic templates. Consecutive pressing switches between different templates |
|
||||||
|
| `Shift+t` | Open template library |
|
||||||
|
| `Alt+r` | Rotate tool |
|
||||||
|
| `Alt+v` | Flip vertically |
|
||||||
|
| `Alt+h` | Flip horizontally |
|
||||||
|
| `Ctrl+g` | S-Group tool / Data S-Group tool |
|
||||||
|
| `Ctrl+d` | Align and select all S-Group data
|
||||||
|
| `Ctrl+r` | Switching between the R-Group Label Tool/R-Group Fragment Tool/Attachment Point Tool |
|
||||||
|
| `Ctrl+Shift+r` | R-Group Fragment Tool |
|
||||||
|
| `Ctrl+Del` | Clear canvas |
|
||||||
|
| `Ctrl+o` | Open |
|
||||||
|
| `Ctrl+s` | Save As |
|
||||||
|
| `Ctrl+z` | Undo |
|
||||||
|
| `Ctrl+Shift+z` | Redo |
|
||||||
|
| `Ctrl+x` | Cut selected objects |
|
||||||
|
| `Ctrl+c` | Copy selected objects |
|
||||||
|
| `Ctrl+v` | Paste selected objects |
|
||||||
|
| `+` | Zoom In |
|
||||||
|
| `-` | Zoom Out |
|
||||||
|
| `Ctrl+l` | Layout |
|
||||||
|
| `Ctrl+Shift+l` | Clean Up |
|
||||||
|
| `Ctrl+p` | Calculate CIP |
|
||||||
|
| `?` | Help |
|
||||||
|
|
||||||
|
**Note** : Please, use `Ctrl+V` to paste the selected object in
|
||||||
|
Google Chrome and Mozilla Firefox browsers.
|
||||||
|
|
||||||
|
**Note 2** : Probably, you have forbidden access to the local storage.
|
||||||
|
If you are using IE10 or IE11 and didn't forbid access to local storage
|
||||||
|
intentionally, you can pay attention here: https://stackoverflow.com/a/20848924
|
||||||
BIN
static/js/ketcher2/doc/inline-edit.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
static/js/ketcher2/doc/main.png
Normal file
|
After Width: | Height: | Size: 34 KiB |
BIN
static/js/ketcher2/doc/miew-menu.png
Normal file
|
After Width: | Height: | Size: 24 KiB |
BIN
static/js/ketcher2/doc/miew.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
static/js/ketcher2/doc/open.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
static/js/ketcher2/doc/periodic-dialog-ext.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
static/js/ketcher2/doc/periodic-dialog.png
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
static/js/ketcher2/doc/periodic-table.png
Normal file
|
After Width: | Height: | Size: 903 B |
BIN
static/js/ketcher2/doc/reaction-types.png
Normal file
|
After Width: | Height: | Size: 5.6 KiB |
BIN
static/js/ketcher2/doc/reaction.png
Normal file
|
After Width: | Height: | Size: 887 B |
BIN
static/js/ketcher2/doc/rgroup-dialog.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
static/js/ketcher2/doc/rgroup-example1.png
Normal file
|
After Width: | Height: | Size: 4.8 KiB |
BIN
static/js/ketcher2/doc/rgroup-example2.png
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
static/js/ketcher2/doc/rgroup-example3.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
static/js/ketcher2/doc/rgroup-example4.png
Normal file
|
After Width: | Height: | Size: 7.4 KiB |
BIN
static/js/ketcher2/doc/rgroup-types.png
Normal file
|
After Width: | Height: | Size: 4.6 KiB |
BIN
static/js/ketcher2/doc/rgroup.png
Normal file
|
After Width: | Height: | Size: 757 B |