Do create action.

@param  mixed $dataset The data set contains data we want to store.

@return mixed

@throws \Exception
@throws \Throwable
777668
protected function doCreate($dataset)
    {
        !$this->useTransaction ?: $this->db->getTransaction(true)->start();

        try {
            $pkName = $this->getKeyName();

            foreach ($dataset as $k => $data) {
                if (!($data instanceof $this->dataClass)) {
                    $data = $this->bindData($data);
                }

                // If data is entity object, try cast values first.
                if ($data instanceof Entity) {
                    $data = $this->castForStore($data);
                }

                $fields = $this->getFields($this->table, false);

                if (!$data->$pkName) {
                    unset($fields[$pkName]);
                }

                // Then recreate a new Entity to force fields limit.
                $entity = new Entity($fields, $data);

                $entity = $this->validValue($entity);

                $this->db->getWriter()->insertOne($this->table, $entity, $pkName, $entity->hasIncrementField());

                $data->$pkName = $entity->$pkName;

                $dataset[$k] = $data;
            }
        } catch (\Throwable $e) {
            !$this->useTransaction ?: $this->db->getTransaction(true)->rollback();

            throw $e;
        }

        !$this->useTransaction ?: $this->db->getTransaction(true)->commit();

        return $dataset;
    }
487786
public function train(Dataset $dataset) : void
    {
        if (!$dataset instanceof Labeled) {
            throw new InvalidArgumentException('This estimator requires a'
                . ' labeled training set.');
        }

        $this->strategy->fit($dataset->labels());

        $this->trained = true;
    }
380494
public function execute(DataSetInterface $dataSet)
    {
        $addressKey = $dataSet[CompanyUnitAddressLabelRelationDataSet::ADDRESS_KEY];
        if (!isset($this->idCompanyUnitAddressCache[$addressKey])) {
            $companyUnitAddressQuery = new SpyCompanyUnitAddressQuery();
            $idCompanyUnitAddress = $companyUnitAddressQuery
                ->select(SpyCompanyUnitAddressTableMap::COL_ID_COMPANY_UNIT_ADDRESS)
                ->findOneByKey($addressKey);

            if (!$idCompanyUnitAddress) {
                throw new CompanyUnitAddressNotFoundException(sprintf('Could not find CompanyUnitAddress with key "%s".', $addressKey));
            }

            $this->idCompanyUnitAddressCache[$addressKey] = $idCompanyUnitAddress;
        }

        $dataSet[CompanyUnitAddressLabelRelationDataSet::ID_COMPANY_UNIT_ADDRESS] = $this->idCompanyUnitAddressCache[$addressKey];
    }
60704
public function saveDataset($key, $dataset)
    {
        $data = $this->session->get(self::KEY);
        $data[$key] = $dataset;
        $this->session->set(self::KEY, $data);
        return $this;
    }
795634
public function createOne($data)
    {
        // Event
        $this->triggerEvent(
            'onBefore' . ucfirst(__FUNCTION__),
            [
                'data' => &$data,
            ]
        );

        $dataset = $this->create($this->bindDataset([$data]));

        $result = $dataset[0];

        // Event
        $this->triggerEvent(
            'onAfter' . ucfirst(__FUNCTION__),
            [
                'result' => &$result,
            ]
        );

        return $result;
    }
119505
public function execute(DataSetInterface $dataSet)
    {
        $quoteEntity = SpyQuoteQuery::create()
            ->filterByKey($dataSet[CartDataSetInterface::KEY_CART])
            ->findOneOrCreate();

        $quoteEntity->fromArray($dataSet->getArrayCopy());
        $quoteEntity
            ->setFkStore($dataSet[CartDataSetInterface::ID_STORE]);

        $quoteEntity->save();
    }
268760
public function train(Dataset $dataset) : void
    {
        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        if ($this->logger) {
            $this->logger->info('Learner init ' . Params::stringify([
                'k' => $this->k,
                'epochs' => $this->epochs,
                'min_change' => $this->minChange,
                'seeder' => $this->seeder,
            ]));
        }

        $samples = $dataset->samples();
        $rotated = $dataset->columns();
    
        $n = $dataset->numRows();

        $this->priors = array_fill(0, $this->k, log(1. / $this->k));

        [$this->means, $this->variances] = $this->initialize($dataset);

        $this->steps = [];

        $prevLoss = INF;

        for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
            $memberships = [];

            foreach ($dataset as $sample) {
                $jll = $this->jointLogLikelihood($sample);

                $memberships[] = array_map('exp', $jll);
            }

            $loss = 0.;

            for ($cluster = 0; $cluster < $this->k; $cluster++) {
                $mHat = array_column($memberships, $cluster);

                $means = $variances = [];

                foreach ($rotated as $values) {
                    $a = $b = $total = 0.;

                    foreach ($values as $i => $value) {
                        $membership = $mHat[$i];

                        $a += $membership * $value;
                        $total += $membership;
                    }

                    $total = $total ?: EPSILON;

                    $mean = $a / $total;

                    foreach ($values as $i => $value) {
                        $b += $mHat[$i] * ($value - $mean) ** 2;
                    }

                    $variance = $b / $total;

                    $means[] = $mean;
                    $variances[] = $variance ?: EPSILON;

                    $loss += $total;
                }

                $prior = array_sum($mHat) / $n;

                $this->means[$cluster] = $means;
                $this->variances[$cluster] = $variances;
                $this->priors[$cluster] = log($prior);
            }

            $this->steps[] = $loss;

            if ($this->logger) {
                $this->logger->info("Epoch $epoch complete, loss=$loss");
            }

            if (is_nan($loss)) {
                break 1;
            }

            if (abs($loss - $prevLoss) < $this->minChange) {
                break 1;
            }

            $prevLoss = $loss;
        }

        if ($this->logger) {
            $this->logger->info('Training complete');
        }
    }
394850
public function execute(DataSetInterface $dataSet): void
    {
        $dataSet[PriceProductMerchantRelationshipDataSetInterface::ID_PRICE_PRODUCT_STORE] = $this->getIdPriceProductStoreEntity($dataSet);
    }
51219
public function execute(DataSetInterface $dataSet)
    {
        $categoryEntity = $this->findOrCreateCategory($dataSet);
        $this->findOrCreateAttributes($categoryEntity, $dataSet);
        $categoryNodeEntity = $this->findOrCreateNode($categoryEntity, $dataSet);

        $this->categoryReader->addCategory($categoryEntity, $categoryNodeEntity);
    }
1240052
public function execute(DataSetInterface $dataSet)
    {
        $iso2Code = $this->getIso2Code($dataSet);
        $iso3Code = $this->getIso3Code($dataSet);

        $idCountry = $this->getIdCountryFromCache($iso2Code, $iso3Code);
        if (!$idCountry) {
            $idCountry = $this->getIdCountryFromDatabase($iso2Code, $iso3Code);
        }

        $dataSet[CompanyUnitAddressDataSet::ID_COUNTRY] = $idCountry;
    }
959146
public function train(Dataset $dataset) : void
    {
        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $this->centroids = $this->seeder->seed($dataset, $this->k);

        $sizes = array_fill(1, $this->k, 0);
        $sizes[0] = $dataset->numRows();

        $this->sizes = $sizes;

        $this->steps = [];

        $this->partial($dataset);
    }
1295448
public function execute(DataSetInterface $dataSet): void
    {
        $merchantRelationshipEntity = SpyMerchantRelationshipQuery::create()
            ->filterByMerchantRelationshipKey($dataSet[MerchantRelationshipDataSetInterface::MERCHANT_RELATIONSHIP_KEY])
            ->findOneOrCreate();

        $merchantRelationshipEntity
            ->setFkMerchant($dataSet[MerchantRelationshipDataSetInterface::ID_MERCHANT])
            ->setFkCompanyBusinessUnit($dataSet[MerchantRelationshipDataSetInterface::ID_COMPANY_BUSINESS_UNIT])
            ->save();

        $this->saveMerchantRelationshipToCompanyBusinessUnit($dataSet, $merchantRelationshipEntity->getPrimaryKey());
    }
485616
public function partial(Dataset $dataset) : void
    {
        if (empty($this->centroids) or empty($this->sizes)) {
            $this->train($dataset);

            return;
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        if ($this->logger) {
            $this->logger->info('Learner init ' . Params::stringify([
                'k' => $this->k,
                'batch_size' => $this->batchSize,
                'kernel' => $this->kernel,
                'epochs' => $this->epochs,
                'min_change' => $this->minChange,
                'seeder' => $this->seeder,
            ]));
        }

        $n = $dataset->numRows();

        $samples = $dataset->samples();
        $labels = array_fill(0, $n, 0);

        $order = range(0, $n - 1);

        $randomize = $n > $this->batchSize ? true : false;

        $previous = INF;

        for ($epoch = 1; $epoch <= $this->epochs; $epoch++) {
            if ($randomize) {
                shuffle($order);

                array_multisort($order, $samples, $labels);
            }

            $sBatches = array_chunk($samples, $this->batchSize, true);
            $lBatches = array_chunk($labels, $this->batchSize, true);

            foreach ($sBatches as $i => $batch) {
                $assignments = array_map([self::class, 'assign'], $batch);

                $lHat = $lBatches[$i];

                foreach ($assignments as $j => $cluster) {
                    $expected = $lHat[$j];

                    if ($cluster !== $expected) {
                        $labels[$j] = $cluster;

                        $this->sizes[$expected]--;
                        $this->sizes[$cluster]++;
                    }
                }

                $strata = Labeled::quick($batch, $lHat)->stratify();

                foreach ($strata as $cluster => $stratum) {
                    $centroid = $this->centroids[$cluster];
                    $size = $this->sizes[$cluster];

                    $step = Matrix::quick($stratum->samples())
                        ->transpose()
                        ->mean()
                        ->asArray();

                    $weight = 1. / ($size ?: EPSILON);

                    foreach ($centroid as $i => &$mean) {
                        $mean = (1. - $weight) * $mean + $weight * $step[$i];
                    }

                    $this->centroids[$cluster] = $centroid;
                }
            }

            $inertia = $this->inertia($samples);

            $this->steps[] = $inertia;

            if ($this->logger) {
                $this->logger->info("Epoch $epoch complete, inertia=$inertia");
            }

            if (is_nan($inertia)) {
                break 1;
            }

            if (abs($previous - $inertia) < $this->minChange) {
                break 1;
            }

            $previous = $inertia;
        }

        if ($this->logger) {
            $this->logger->info('Training complete');
        }
    }
194102
public function append(Dataset $dataset) : Dataset
    {
        return self::quick(array_merge($this->samples, $dataset->samples()));
    }
473541
public function execute(DataSetInterface $dataSet): void
    {
        $dataSet = $this->filterDataSet($dataSet);

        $spyProductQuantityEntity = $this->saveProductQuantity($dataSet);

        $this->addPublishEvents(ProductQuantityEvents::PRODUCT_QUANTITY_PUBLISH, $spyProductQuantityEntity->getFkProduct());
    }
664596
public function train(Dataset $dataset) : void
    {
        if ($this->type() === self::CLASSIFIER or $this->type() === self::REGRESSOR) {
            if (!$dataset instanceof Labeled) {
                throw new InvalidArgumentException('This estimator requires a'
                    . ' labeled training set.');
            }
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $p = (int) round($this->ratio * $dataset->numRows());

        $this->ensemble = [];

        Loop::run(function () use ($dataset, $p) {
            $pool = new DefaultPool($this->workers);

            $coroutines = [];

            for ($i = 0; $i < $this->estimators; $i++) {
                $estimator = clone $this->base;

                $subset = $dataset->randomSubsetWithReplacement($p);

                $task = new CallableTask(
                    [$this, '_train'],
                    [$estimator, $subset]
                );

                $coroutines[] = call(function () use ($pool, $task) {
                    return yield $pool->enqueue($task);
                });
            }

            $this->ensemble = yield all($coroutines);
            
            return yield $pool->shutdown();
        });
    }
1209964
public function fit(Dataset $dataset) : void
    {
        $this->strategies = [];

        foreach ($dataset->types() as $column => $type) {
            $values = [];

            foreach ($dataset->column($column) as $value) {
                if ($value !== $this->placeholder) {
                    $values[] = $value;
                }
            }

            switch ($type) {
                case DataType::CATEGORICAL:
                    $strategy = clone $this->categorical;
                    break 1;

                case DataType::CONTINUOUS:
                    $strategy = clone $this->continuous;
                    break 1;

                default:
                    throw new InvalidArgumentException('This transformer'
                        . ' only handles categorical and continuous'
                        . ' features, ' . DataType::TYPES[$type]
                        . ' found.');
            }

            $strategy->fit($values);

            $this->strategies[$column] = $strategy;
        }
    }