Package com.opengamma.engine.view.compilation

Examples of com.opengamma.engine.view.compilation.CompiledViewDefinitionWithGraphs


    _structuredSnappers = new StructuredSnapper[] {_yieldCurveSnapper, _curveSnapper, _volatilitySurfaceSnapper, _volatilityCubeSnapper };
  }

  @Override
  public StructuredMarketDataSnapshot createSnapshot(final ViewClient client, final ViewCycle cycle) {
    final CompiledViewDefinitionWithGraphs defn = cycle.getCompiledViewDefinition();
    final ComputationTargetResolver.AtVersionCorrection resolver = _resolver.atVersionCorrection(cycle.getResultModel().getVersionCorrection());
    return createSnapshot(new ExternalIdBundleResolver(resolver), cycle.getResultModel(), getGraphs(defn), cycle, defn.getViewDefinition().getName());
  }
View Full Code Here


  // TODO: snapshot should be holding value specifications not value requirements

  @Override
  public Map<YieldCurveKey, Map<String, ValueRequirement>> getYieldCurveSpecifications(final ViewClient client, final ViewCycle cycle) {
    final CompiledViewDefinitionWithGraphs defn = cycle.getCompiledViewDefinition();
    final Map<String, DependencyGraph> graphs = getGraphs(defn);

    final Map<YieldCurveKey, Map<String, ValueRequirement>> ret = new HashMap<YieldCurveKey, Map<String, ValueRequirement>>();
    for (final Entry<String, DependencyGraph> entry : graphs.entrySet()) {
      final DependencyGraph graph = entry.getValue();
View Full Code Here

    //
    // if the engine and the web components are in a different VM then compiledViewDef won't be an instance of
    // CompiledViewDefinitionWithGraphs and the hack won't work. in that case the view cycle will be empty and the
    // user won't see a dependency graph if this is called before the first set of results arrives.
    // as soon as the first set of results arrives it will work the same as if all the components are in the same VM
    CompiledViewDefinitionWithGraphs viewDef;
    if (compiledViewDef instanceof CompiledViewDefinitionWithGraphs) {
      viewDef = (CompiledViewDefinitionWithGraphs) compiledViewDef;
    } else {
      viewDef = cycle.getCompiledViewDefinition();
    }
    DependencyGraphExplorer depGraphExplorer = viewDef.getDependencyGraphExplorer(calcConfigName);
    DependencyGraph depGraph = depGraphExplorer.getSubgraphProducing(rootSpec);
    AnalyticsNode node = createNode(rootSpec, depGraph, true);
    _structure = new DependencyGraphGridStructure(node, calcConfigName, requirement, _valueSpecs, _fnNames, targetResolver);
  }
View Full Code Here

        checkForRecompilation(context, compiled);
        return true;
      }
      if (getSecondary() == context) {
        s_logger.info("View definition compiled by secondary worker");
        CompiledViewDefinitionWithGraphs primaryCompile = getPrimary()._lastCompiled;
        final Map<ComputationTargetReference, UniqueId> primaryResolutions = primaryCompile.getResolvedIdentifiers();
        final Map<ComputationTargetReference, UniqueId> secondaryResolutions = compiled.getResolvedIdentifiers();
        if (primaryResolutions.equals(secondaryResolutions)) {
          // Nothing has changed, the primary is still valid
          s_logger.debug("Rejecting compilation from secondary worker");
          _secondary = null;
View Full Code Here

    if (latestCompilation != null) {
      // [PLAT-1158] The initial notification is performed outside of holding the lock which avoids the deadlock problem, but we'll still
      // block for completion which was the thing PLAT-1158 was trying to avoid. This is because the contracts for the order in which
      // notifications can be received is unclear and I don't want to risk introducing a change at this moment in time.
      try {
        final CompiledViewDefinitionWithGraphs compiledViewDefinition = latestCompilation.getFirst();
        final MarketDataPermissionProvider permissionProvider = latestCompilation.getSecond();
        final Set<ValueSpecification> marketData = compiledViewDefinition.getMarketDataRequirements();
        final Set<ValueSpecification> deniedRequirements =
            permissionProvider.checkMarketDataPermissions(listener.getUser(), marketData);
        final boolean hasMarketDataPermissions = deniedRequirements.isEmpty();
        listener.viewDefinitionCompiled(compiledViewDefinition, hasMarketDataPermissions);
        if (latestResult != null) {
View Full Code Here

  }

  private CompiledViewDefinitionWithGraphs getCompiledViewDefinition(final Instant valuationTime, final VersionCorrection versionCorrection) {
    final long functionInitId = getProcessContext().getFunctionCompilationService().getFunctionCompilationContext().getFunctionInitId();
    updateViewDefinitionIfRequired();
    CompiledViewDefinitionWithGraphs compiledViewDefinition = null;
    final Pair<Lock, Lock> executionCacheLocks = getProcessContext().getExecutionCacheLock().get(_executionCacheKey, valuationTime, versionCorrection);
    executionCacheLocks.getSecond().lock();
    executionCacheLocks.getFirst().lock();
    boolean broadLock = true;
    try {
      Map<String, Pair<DependencyGraph, Set<ValueRequirement>>> previousGraphs = null;
      ConcurrentMap<ComputationTargetReference, UniqueId> previousResolutions = null;
      Set<UniqueId> changedPositions = null;
      Set<UniqueId> unchangedNodes = null;
      if (!_forceGraphRebuild) {
        compiledViewDefinition = getCachedCompiledViewDefinition(valuationTime, versionCorrection);
        boolean marketDataProviderDirty = _marketDataManager.isMarketDataProviderDirty();
        _marketDataManager.markMarketDataProviderClean();
        if (compiledViewDefinition != null) {
          executionCacheLocks.getFirst().unlock();
          broadLock = false;
          do {
            // The cast below is bad, but only temporary -- the function initialiser id needs to go
            if (functionInitId != ((CompiledViewDefinitionWithGraphsImpl) compiledViewDefinition).getFunctionInitId()) {
              // The function repository has been reinitialized which invalidates any previous graphs
              // TODO: [PLAT-2237, PLAT-1623, PLAT-2240] Get rid of this
              break;
            }
            final Map<ComputationTargetReference, UniqueId> resolvedIdentifiers = compiledViewDefinition.getResolvedIdentifiers();
            // TODO: The check below works well for the historical valuation case, but if the resolver v/c is different for two workers in the
            // group for an otherwise identical cache key then including it in the caching detail may become necessary to handle those cases.
            if (!versionCorrection.equals(compiledViewDefinition.getResolverVersionCorrection())) {
              final Map<UniqueId, ComputationTargetSpecification> invalidIdentifiers = getInvalidIdentifiers(resolvedIdentifiers, versionCorrection);
              if (invalidIdentifiers != null) {
                previousGraphs = getPreviousGraphs(previousGraphs, compiledViewDefinition);
                if ((compiledViewDefinition.getPortfolio() != null) && invalidIdentifiers.containsKey(compiledViewDefinition.getPortfolio().getUniqueId())) {
                  // The portfolio resolution is different, invalidate or rewrite PORTFOLIO and PORTFOLIO_NODE nodes in the graph. Note that incremental
                  // compilation under this circumstance can be flawed if the functions have made notable use of the overall portfolio structure such that
                  // a full re-compilation will yield a different dependency graph to just rewriting the previous one.
                  final ComputationTargetResolver resolver = getProcessContext().getFunctionCompilationService().getFunctionCompilationContext().getRawComputationTargetResolver();
                  final ComputationTargetSpecification portfolioSpec = resolver.getSpecificationResolver().getTargetSpecification(
                      new ComputationTargetSpecification(ComputationTargetType.PORTFOLIO, getViewDefinition().getPortfolioId()), versionCorrection);
                  final ComputationTarget newPortfolio = resolver.resolve(portfolioSpec, versionCorrection);
                  unchangedNodes = rewritePortfolioNodes(previousGraphs, compiledViewDefinition, (Portfolio) newPortfolio.getValue());
                }
                // Invalidate any dependency graph nodes on the invalid targets
                filterPreviousGraphs(previousGraphs, new InvalidTargetDependencyNodeFilter(invalidIdentifiers.keySet()), unchangedNodes);
                previousResolutions = new ConcurrentHashMap<>(resolvedIdentifiers.size());
                for (final Map.Entry<ComputationTargetReference, UniqueId> resolvedIdentifier : resolvedIdentifiers.entrySet()) {
                  if (invalidIdentifiers.containsKey(resolvedIdentifier.getValue())) {
                    if ((unchangedNodes == null) && resolvedIdentifier.getKey().getType().isTargetType(ComputationTargetType.POSITION)) {
                      // At least one position has changed, add all portfolio targets
                      ComputationTargetSpecification ctspec = invalidIdentifiers.get(resolvedIdentifier.getValue());
                      if (ctspec != null) {
                        if (changedPositions == null) {
                          changedPositions = new HashSet<>();
                        }
                        changedPositions.add(ctspec.getUniqueId());
                      }
                    }
                  } else {
                    previousResolutions.put(resolvedIdentifier.getKey(), resolvedIdentifier.getValue());
                  }
                }
              } else {
                compiledViewDefinition = compiledViewDefinition.withResolverVersionCorrection(versionCorrection);
                cacheCompiledViewDefinition(compiledViewDefinition);
              }
            }
            if (!CompiledViewDefinitionWithGraphsImpl.isValidFor(compiledViewDefinition, valuationTime)) {
              // Invalidate any dependency graph nodes that use functions that are no longer valid
              previousGraphs = getPreviousGraphs(previousGraphs, compiledViewDefinition);
              filterPreviousGraphs(previousGraphs, new InvalidFunctionDependencyNodeFilter(valuationTime), unchangedNodes);
            }
            if (marketDataProviderDirty) {
              previousGraphs = invalidateMarketDataSourcingNodes(previousGraphs, compiledViewDefinition, versionCorrection, unchangedNodes);
            }
            if (previousGraphs == null) {
              // Existing cached model is valid (an optimization for the common case of similar, increasing valuation times)
              return compiledViewDefinition;
            }
            if (previousResolutions == null) {
              previousResolutions = new ConcurrentHashMap<>(resolvedIdentifiers);
            }
          } while (false);
          executionCacheLocks.getFirst().lock();
          broadLock = true;
        }
      }
      final MarketDataAvailabilityProvider availabilityProvider = _marketDataManager.getAvailabilityProvider();
      final ViewCompilationServices compilationServices = getProcessContext().asCompilationServices(availabilityProvider);
      if (previousGraphs != null) {
        s_logger.info("Performing incremental graph compilation");
        _compilationTask = ViewDefinitionCompiler.incrementalCompileTask(getViewDefinition(), compilationServices, valuationTime, versionCorrection, previousGraphs, previousResolutions,
            changedPositions, unchangedNodes);
      } else {
        s_logger.info("Performing full graph compilation");
        _compilationTask = ViewDefinitionCompiler.fullCompileTask(getViewDefinition(), compilationServices, valuationTime, versionCorrection);
      }
      try {
        if (!getJob().isTerminated()) {
          compiledViewDefinition = _compilationTask.get();
          ComputationTargetResolver.AtVersionCorrection resolver = getProcessContext().getFunctionCompilationService().getFunctionCompilationContext().getRawComputationTargetResolver()
              .atVersionCorrection(versionCorrection);
          compiledViewDefinition = initialiseMarketDataManipulation(compiledViewDefinition, resolver);
          cacheCompiledViewDefinition(compiledViewDefinition);
        } else {
          return null;
        }
      } finally {
        _compilationTask = null;
      }
    } catch (final Exception e) {
      final String message = MessageFormat.format("Error compiling view definition {0} for time {1}",
          getViewDefinition().getUniqueId(),
          valuationTime);
      viewDefinitionCompilationFailed(valuationTime, new OpenGammaRuntimeException(message, e));
      throw new OpenGammaRuntimeException(message, e);
    } finally {
      _forceGraphRebuild = false;
      if (broadLock) {
        executionCacheLocks.getFirst().unlock();
      }
      executionCacheLocks.getSecond().unlock();
    }
    // [PLAT-984]
    // Assume that valuation times are increasing in real-time towards the expiry of the view definition, so that we
    // can predict the time to expiry. If this assumption is wrong then the worst we do is trigger an unnecessary
    // cycle. In the predicted case, we trigger a cycle on expiry so that any new market data subscriptions are made
    // straight away.
    if ((compiledViewDefinition.getValidTo() != null) && getExecutionOptions().getFlags().contains(ViewExecutionFlags.TRIGGER_CYCLE_ON_MARKET_DATA_CHANGED)) {
      final Duration durationToExpiry = _marketDataManager.getMarketDataProvider().getRealTimeDuration(valuationTime,
          compiledViewDefinition.getValidTo());
      final long expiryNanos = System.nanoTime() + durationToExpiry.toNanos();
      _compilationExpiryCycleTrigger.set(expiryNanos, ViewCycleTriggerResult.forceFull());
      // REVIEW Andrew 2012-11-02 -- If we are ticking live, then this is almost right (System.nanoTime will be close to valuationTime, depending on how
      // long the compilation took). If we are running through historical data then this is quite a meaningless trigger.
    } else {
View Full Code Here

   * @param valuationTime the indicative valuation time, not null
   * @param resolverVersionCorrection the resolver version correction, not null
   * @return the cached compiled view definition, or null if nothing is currently cached
   */
  public CompiledViewDefinitionWithGraphs getCachedCompiledViewDefinition(final Instant valuationTime, final VersionCorrection resolverVersionCorrection) {
    CompiledViewDefinitionWithGraphs cached = _latestCompiledViewDefinition;
    if (cached != null) {
      boolean resolverMatch = resolverVersionCorrection.equals(cached.getResolverVersionCorrection());
      boolean valuationMatch = CompiledViewDefinitionWithGraphsImpl.isValidFor(cached, valuationTime);
      if (!resolverMatch || !valuationMatch) {
        // Query the cache in case there is a newer one
        cached = getProcessContext().getExecutionCache().getCompiledViewDefinitionWithGraphs(_executionCacheKey);
        if (cached != null) {
          // Only update ours if the one from the cache has a better validity
          if (resolverVersionCorrection.equals(cached.getResolverVersionCorrection())) {
            cached = PLAT3249.deepClone(cached);
            _latestCompiledViewDefinition = cached;
          } else {
            if (!resolverMatch && !valuationMatch && CompiledViewDefinitionWithGraphsImpl.isValidFor(cached, valuationTime)) {
              cached = PLAT3249.deepClone(cached);
View Full Code Here

  public void onMarketDataValuesChanged(final Collection<ValueSpecification> valueSpecifications) {
    if (!getExecutionOptions().getFlags().contains(ViewExecutionFlags.TRIGGER_CYCLE_ON_MARKET_DATA_CHANGED)) {
      return;
    }
    // Don't want to query the cache for this; always use the last one
    final CompiledViewDefinitionWithGraphs compiledView = _latestCompiledViewDefinition;
    if (compiledView == null) {
      return;
    }
    if (CollectionUtils.containsAny(compiledView.getMarketDataRequirements(), valueSpecifications)) {
      requestCycle();
    }
  }
View Full Code Here

      }

      final VersionCorrection versionCorrection = getResolverVersionCorrection(executionOptions);
      VersionCorrectionUtils.lock(versionCorrection);
      try {
        final CompiledViewDefinitionWithGraphs compiledViewDefinition;
        try {
          // Don't query the cache so that the process gets a "compiled" message even if a cached compilation is used
          final CompiledViewDefinitionWithGraphs previous = _latestCompiledViewDefinition;
          if (_ignoreCompilationValidity && (previous != null) && CompiledViewDefinitionWithGraphsImpl.isValidFor(previous, compilationValuationTime)) {
            compiledViewDefinition = previous;
          } else {
            compiledViewDefinition = getCompiledViewDefinition(compilationValuationTime, versionCorrection);
            if (compiledViewDefinition == null) {
              s_logger.warn("Job terminated during view compilation");
              return;
            }
            if ((previous == null) || !previous.getCompilationIdentifier().equals(compiledViewDefinition.getCompilationIdentifier())) {
              if (_targetResolverChanges != null) {
                // We'll try to register for changes that will wake us up for a cycle if market data is not ticking
                if (previous != null) {
                  final Set<UniqueId> subscribedIds = new HashSet<>(previous.getResolvedIdentifiers().values());
                  for (UniqueId uid : compiledViewDefinition.getResolvedIdentifiers().values()) {
                    if (!subscribedIds.contains(uid)) {
                      _targetResolverChanges.watch(uid.getObjectId());
                    }
                  }
View Full Code Here

   */
  private final Map<ViewExecutionCacheKey, CompiledViewDefinitionWithGraphs> _compiledViewDefinitions = new MapMaker().softValues().makeMap();

  @Override
  public CompiledViewDefinitionWithGraphs getCompiledViewDefinitionWithGraphs(ViewExecutionCacheKey key) {
    CompiledViewDefinitionWithGraphs viewDefinition = _compiledViewDefinitions.get(key);
    if (s_logger.isDebugEnabled()) {
      if (viewDefinition == null) {
        s_logger.debug("Cache miss CompiledViewDefinitionWithGraphs for {}", key);
      } else {
        s_logger.debug("Cache hit CompiledViewDefinitionWithGraphs for {}", key);
View Full Code Here

TOP

Related Classes of com.opengamma.engine.view.compilation.CompiledViewDefinitionWithGraphs

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.