Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OG-609 orthologs to purple form #46

Draft
wants to merge 5 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 72 additions & 5 deletions app/assets/js/gene.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,12 +177,79 @@ $(document).on('click', '#experiments-form .js-experiment-short', function() {

$(document).on('click', '#experiments-form .js-lifespan-experiment-short', function() {
let modelId = $(this).attr('model-id')
let container = $(this).closest('.js-short-form-container')
let container = $(this).closest('.js-short-form-container')
$.get('/gene/load-widget-form?modelName=LifespanExperiment&widgetName=GeneralLifespanExperimentWidget&id='
+modelId
+'&modelParams[gene_id]='+$(this).attr('gene-id')
+'&modelParams[type]=experiment'
+'&geneId='+$(this).attr('gene-id'), function (data) {
+ modelId
+ '&modelParams[gene_id]=' + $(this).attr('gene-id')
+ '&modelParams[type]=experiment'
+ '&geneId=' + $(this).attr('gene-id'), function (data) {
container.html(data);
})
})

//ортологи в эксперименты
$(document).on('change', '#experiments-form .js-lifespan-experiment-block [id$="model_organism_id"]', function() {
let t = $(this);
let model_organism_id = t.val();
let gene_id = $('.js-lifespan-experiment-block [name$="[currentGeneId]"]').val();
$.get('/gene/get-orthologs?modelOrganismId='+model_organism_id+'&geneId='+gene_id, function (data) {
let orthologs = JSON.parse(data);
let select = t.parents('.js-lifespan-experiment').find('.js-lifespan-experiments-gene .orthologs');
select.empty();
let options = Object.entries(orthologs);
for (const [id, symbol] of options) {
select.append($('<option>', {
value: id,
text: symbol
}));
}
if (options.length == 1) {
select.val(options[0][0]);
}
select.change();
});
});

//запрет изменения организма при существующем доп воздействии
$(document).on('click', '.js-add-lifespan-experiment-control, .js-add-lifespan-experiment-gene', function() {
let t = $(this);
let general_le_name = t.parents('.js-gene-link-section').find('input[name^="GeneralLifespanExperiment"')[0].name;
let matches = general_le_name.match(/GeneralLifespanExperiment\[(\d+)\]\[(\w+)\]/);
let general_le_id = matches[1];
let select = $('select#generallifespanexperiment-'+general_le_id+'-model_organism_id');

select.data('data-value', select.val())
$('select#generallifespanexperiment-'+general_le_id+'-model_organism_id').next().children().each(function () {
$(this).css('pointer-events', 'none');
});
$('#select2-generallifespanexperiment-'+general_le_id+'-model_organism_id-container')
.parents('[aria-labelledby="select2-generallifespanexperiment-'+general_le_id+'-model_organism_id-container"]')
.css('background-color', '#d6d8d9').css('border-color', '#c6c8ca');
$('#select2-generallifespanexperiment-'+general_le_id+'-model_organism_id-container .select2-selection__clear').css('display', 'none');
})

//ортологи при изменении гена в доп воздействии
$(document).on('change', '.js-lifespan-experiment [id$="gene_id"]', function() {
let t = $(this);
let gene_id = t.val();
let select = t.parents('.js-lifespan-experiment').parents('.js-lifespan-experiment').find('[id$="model_organism_id"]');
console.log(select);
let model_organism_id = select.data('data-value');

$.get('/gene/get-orthologs?modelOrganismId='+model_organism_id+'&geneId='+gene_id, function (data) {
let orthologs = JSON.parse(data);
let select = t.parents('.gene-modulation.js-gene-link-section').find('.orthologs');
select.empty();
let options = Object.entries(orthologs);
for (const [id, symbol] of options) {
select.append($('<option>', {
value: id,
text: symbol
}));
}
if (options.length == 1) {
select.val(options[0][0]);
}
select.change();
});
});
7 changes: 6 additions & 1 deletion app/controllers/GeneController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use app\models\GeneToAdditionalEvidence;
use app\models\GeneToLongevityEffect;
use app\models\GeneToProgeria;
use app\models\Ortholog;
use app\models\Phylum;
use app\models\CommentCause;
use app\models\Gene;
Expand Down Expand Up @@ -47,7 +48,7 @@ public function behaviors()
'rules' => [
[
'allow' => true,
'actions' => ['index', 'update', 'update-experiments', 'update-functions', 'update-age-related-changes', 'load-widget-form'],
'actions' => ['index', 'update', 'update-experiments', 'update-functions', 'update-age-related-changes', 'load-widget-form', 'get-orthologs'],
'roles' => ['admin', 'editor', 'contributor'],
],
[
Expand Down Expand Up @@ -233,6 +234,10 @@ public function actionLoadWidgetForm($id, string $modelName, string $widgetName,
return $this->renderAjax('_geneLinkWidgetForm', ['model' => $model, 'widgetName' => $widgetName, 'params' => $params]);
}

public function actionGetOrthologs(int $modelOrganismId, int $geneId) {
return json_encode(Ortholog::getByOrganismAndGene($modelOrganismId, $geneId));
}

/**
* Finds the Gene model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
Expand Down
58 changes: 58 additions & 0 deletions app/migrations/m220325_103131_lifespan_experiment_to_ortholog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

use yii\db\Migration;
use yii\db\Schema;

/**
* Class m220325_103131_lifespan_experiment_to_ortholog
*/
class m220325_103131_lifespan_experiment_to_ortholog extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('lifespan_experiment_to_ortholog', [
'id' => Schema::TYPE_PK,
'lifespan_experiment_id' => Schema::TYPE_INTEGER,
'ortholog_id' => Schema::TYPE_INTEGER,
], 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB');

$this->addForeignKey('le_to_ortholog_to_le', 'lifespan_experiment_to_ortholog', 'lifespan_experiment_id', 'lifespan_experiment', 'id', 'CASCADE');
$this->addForeignKey('le_to_ortholog_to_ortholog', 'lifespan_experiment_to_ortholog', 'ortholog_id', 'ortholog', 'id', 'CASCADE');

Yii::$app->db->createCommand(
'INSERT INTO lifespan_experiment_to_ortholog (lifespan_experiment_id, ortholog_id)
SELECT le.id, o.id FROM lifespan_experiment le
JOIN general_lifespan_experiment gle ON le.general_lifespan_experiment_id = gle.id
JOIN ortholog o ON gle.model_organism_id=o.model_organism_id
JOIN gene_to_ortholog gto ON o.id = gto.ortholog_id
WHERE le.gene_id = gto.gene_id');
}

/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropForeignKey('le_to_ortholog_to_le', 'lifespan_experiment_to_ortholog');
$this->dropForeignKey('le_to_ortholog_to_ortholog', 'lifespan_experiment_to_ortholog');
$this->dropTable('lifespan_experiment_to_ortholog');
}

/*
// Use up()/down() to run migration code without a transaction.
public function up()
{

}

public function down()
{
echo "m220325_103131_lifespan_experiment_to_ortholog cannot be reverted.\n";

return false;
}
*/
}
151 changes: 139 additions & 12 deletions app/models/LifespanExperiment.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
use app\models\behaviors\ChangelogBehavior;
use app\models\common\GeneralLifespanExperimentQuery;
use app\models\common\LifespanExperimentQuery;
use app\models\common\LifespanExperimentToOrtholog;
use app\models\exceptions\UpdateExperimentsException;
use app\models\traits\ExperimentsActiveRecordTrait;
use app\models\traits\ValidatorsTrait;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
Expand All @@ -21,9 +23,13 @@ class LifespanExperiment extends common\LifespanExperiment
use ValidatorsTrait;
use ExperimentsActiveRecordTrait;

public const TYPE_ORTHOLOG = 1;
public const TYPE_TISSUE = 2;
public $delete = false;
public $tissuesIds;
private $tissuesIdsArray;
private $orthologIds = [];
private $modelOrganismId;

public function behaviors()
{
Expand Down Expand Up @@ -58,7 +64,7 @@ public function rules()
return ArrayHelper::merge(
parent::rules(), [
[['gene_id', 'gene_intervention_method_id'], 'safe'], // todo OG-410
[['tissuesIds', 'intervention_result_id'], 'safe'],
[['tissuesIds', 'intervention_result_id', 'orthologIds'], 'safe'],
[['age'], 'number', 'min' => 0],
[['reference'], 'validateDOI']
]);
Expand Down Expand Up @@ -107,7 +113,14 @@ public function beforeValidate()

return parent::beforeValidate();
}
public function afterSave($insert, $changedAttributes)
{
if (Yii::$app instanceof \yii\console\Application) { // todo продумать нормальный фикс
return parent::afterSave($insert, $changedAttributes);
}

parent::afterSave($insert, $changedAttributes);
}

/**
* Gets query for [[GeneralLifespanExperiment]].
Expand Down Expand Up @@ -174,6 +187,8 @@ public static function saveMultipleForGene(array $modelArrays)
self::setAttributeFromNewAR($modelArray, 'treatment_end_stage_of_development_id', 'TreatmentStageOfDevelopment', $modelAR);
self::setAttributeFromNewAR($modelArray, 'genotype', 'Genotype', $modelAR);

// Ortholog::createNewByIds($modelArray['orthologIds'], $modelAR->general_lifespan_experiment_id, $modelAR->gene_id);

if ($modelAR->organism_line_id === '') {
$modelAR->organism_line_id = null;
}
Expand All @@ -183,10 +198,58 @@ public static function saveMultipleForGene(array $modelArrays)
if (!$modelAR->validate() || !$modelAR->save()) {
throw new UpdateExperimentsException($id, $modelAR);
}
$modelAR->saveTissues($modelArray['tissuesIdsArray']);
$modelAR->saveForeignEntity(self::TYPE_TISSUE, $modelArray['tissuesIdsArray']);
// $modelAR->saveTissues($modelArray['tissuesIdsArray']);
// $modelAR->saveOrthologs($modelArray['orthologIds']);
$modelAR->saveForeignEntity(self::TYPE_ORTHOLOG,
$modelArray['orthologIds'],
$modelAR->general_lifespan_experiment_id,
$modelAR->gene_id
);
}
}

public function getTissuesIdsArray()
{
return LifespanExperimentToTissue::find()
->select('tissue_id')
->where(['lifespan_experiment_id' => $this->id])
->asArray()
->column();
}

public function setTissuesIdsArray(array $ids)
{
$this->tissuesIdsArray = $ids;
}
public function setOrthologIds($ids)
{
if (!$ids) {
$ids = [];
}
$this->orthologIds = $ids;
}

public function getOrthologIds()
{
return LifespanExperimentToOrtholog::find()
->select('ortholog_id')
->where(['lifespan_experiment_id' => $this->id])
->asArray()
->column();
}

public function setModelOrganismId($id)
{
$this->modelOrganismId = $id;
}

public function getModelOrganismId()
{
return $this->getGeneralLifespanExperiment()
->select('model_organism_id')->distinct()->one()->model_organism_id;
}

private function saveTissues($tissuesIdsArray)
{
$currentTissuesIdsArray = $this->getTissuesIdsArray();
Expand Down Expand Up @@ -220,19 +283,83 @@ private function saveTissues($tissuesIdsArray)
}
}


public function getTissuesIdsArray()
private function saveOrthologs($orthologIds, $typeRelations, $generalLe = false, $geneId = false)
{
return LifespanExperimentToTissue::find()
->select('tissue_id')
->where(['lifespan_experiment_id' => $this->id])
->asArray()
->column();
$currentOrthologIds = $this->getOrthologIds();

if ($currentOrthologIds !== $orthologIds) {
if ($orthologIds) {
$orthologIdsToDelete = array_diff($currentOrthologIds, $orthologIds);
$orthologIdsToAdd = array_diff($orthologIds, $currentOrthologIds);

foreach ($orthologIdsToAdd as $orthologIdToAdd) {
if (!is_numeric($orthologIdToAdd)) {
$orthologToAdd = Ortholog::createNewByName($orthologIdToAdd, $generalLe, $geneId);
$orthologIdToAdd = $orthologToAdd->id;
}
$lifespanExperimentToTissue = new LifespanExperimentToOrtholog();
$lifespanExperimentToTissue->lifespan_experiment_id = $this->id;
$lifespanExperimentToTissue->tissue_id = $orthologIdToAdd;
$lifespanExperimentToTissue->save();
}
} else {
$orthologIdsToDelete = $currentOrthologIds;
}

$arsToDelete = LifespanExperimentToOrtholog::find()->where(
['and', ['lifespan_experiment_id' => $this->id],
['in', 'ortholog_id', $orthologIdsToDelete]]
)->all();
foreach ($arsToDelete as $arToDelete) { // one by one for properly triggering "afterDelete" event
$arToDelete->delete();
}
}
}

public function setTissuesIdsArray(array $ids)
private function saveForeignEntity($typeRelations, $newIds, $generalLe = false, $geneId = false)
{
$this->tissuesIdsArray = $ids;
}
if($typeRelations == 1) {
$relationKey = 'ortholog_id';
$relationClass = LifespanExperimentToOrtholog::class;
$currentIds = $this->getOrthologIds();
}
elseif($typeRelations == 2){
$relationKey = 'tissue_id';
$relationClass = LifespanExperimentToTissue::class;
$currentIds = $this->getTissuesIdsArray();
}

if ($currentIds !== $newIds) {
if ($newIds) {
$IdsToDelete = array_diff($currentIds, $newIds);
$idsToAdd = array_diff($newIds, $currentIds);

foreach ($idsToAdd as $idToAdd) {
if (!is_numeric($idToAdd)) {
if ($typeRelations == 1) {
$entityToAdd = Ortholog::createNewByName($idToAdd, $generalLe, $geneId);
}
elseif($typeRelations == 2) {
$entityToAdd = Sample::createFromNameString($idToAdd);
}
$idToAdd = $entityToAdd->id;
}
$lifespanExperimentToEntity = new $relationClass;
$lifespanExperimentToEntity->lifespan_experiment_id = $this->id;
$lifespanExperimentToEntity->$relationKey = $idToAdd;
$lifespanExperimentToEntity->save();
}
} else {
$IdsToDelete = $currentIds;
}

$arsToDelete = $relationClass::find()->where(
['and', ['lifespan_experiment_id' => $this->id],
['in', $relationKey, $IdsToDelete]]
)->all();
foreach ($arsToDelete as $arToDelete) { // one by one for properly triggering "afterDelete" event
$arToDelete->delete();
}
}
}
}
Loading