public void refreshFromDB(String newName) { if (_mainObject.getName().equals(newName)) { if (_mainObject instanceof ICatalogObject) { if (_mainObject instanceof SybaseASABaseUserDefinedType) { Schema schema = ((UserDefinedType) _mainObject).getSchema(); // schema may lost if (schema == null) { _mainObject = null; return; } } ((ICatalogObject) _mainObject).refresh(); return; } } if (!isModelExist()) { _mainObject = null; return; } boolean isFound = false; if (_mainObject instanceof SybaseASABaseUserDefinedType) { Schema schema = ((SybaseASABaseUserDefinedType) _mainObject).getSchema(); // schema may lost if (schema != null) { // DSEUtil.refreshObjectBySchema(schema, _mainObject); EList udds = schema.getUserDefinedTypes(); for (Iterator iter = udds.iterator(); iter.hasNext(); ) { SybaseASABaseUserDefinedType asaUDD = (SybaseASABaseUserDefinedType) iter.next(); if (asaUDD.getName().equals(_mainObject.getName())) { _mainObject = asaUDD; isFound = true; break; } } if (!isFound) { for (Iterator iter = udds.iterator(); iter.hasNext(); ) { SybaseASABaseUserDefinedType asaUDD = (SybaseASABaseUserDefinedType) iter.next(); if (asaUDD.getName().equals(newName)) { _mainObject = asaUDD; isFound = true; break; } } } } } if (!isFound) { _mainObject = null; } }
/* * (non-Javadoc) * * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ public Object execute(ExecutionEvent event) throws ExecutionException { Project p = MovieUtil.getActiveProject(); if (p != null) { EList<Movie> movies = p.getAllModelElementsbyClass(MoviesPackage.eINSTANCE.getMovie(), new BasicEList<Movie>()); for (Iterator<Movie> iter = movies.iterator(); iter.hasNext(); ) { if (iter.next().getOverallRating() == "ZERO" || iter.next().getOverallRating() == "ONE" || iter.next().getOverallRating() == "TWO") { iter.remove(); } } // Open Movies View and set input try { IViewPart view = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .showView(MoviesView.ID); if (view instanceof MoviesView) { MoviesView moviesView = (MoviesView) view; moviesView.setInput(movies); } } catch (PartInitException e) { // showView() can throw an exception if view cannot be shown e.printStackTrace(); } } return null; }
public static Preference getPreferenceByID( DefaultProfile defaultProfile, String categoryId, String prefId) { Category cat = getCategoryByID(defaultProfile, categoryId); if (cat != null) { // if found category EList groups = cat.getGroup(); for (Iterator grpIt = groups.iterator(); grpIt.hasNext(); ) { Group group = (Group) grpIt.next(); EList prefs = group.getPref(); for (Iterator it = prefs.iterator(); it.hasNext(); ) { Preference pref = (Preference) it.next(); if (prefId.equals(pref.getId())) return pref; } } } return null; }
private static Category getCategoryByID(DefaultProfile defaultProfile, String categoryId) { EList cats = defaultProfile.getCategory(); for (Iterator it = cats.iterator(); it.hasNext(); ) { Category cat = (Category) it.next(); if (categoryId.equals(cat.getId())) return cat; } return null; }
private static void getAllSuperClasses(EClass eClass, Set<EClass> result) { EList superTypes = eClass.getESuperTypes(); for (Iterator it = superTypes.iterator(); it.hasNext(); ) { EClass element = (EClass) it.next(); result.add(element); getAllSuperClasses(element, result); } }
private int[] initDomainValues(DiscreteDomain domain) { EList<DomainValue> values = domain.getValues(); int[] valueArray = new int[values.size()]; Iterator<DomainValue> iterator = values.iterator(); for (int i = 0; i < valueArray.length; i++) { valueArray[i] = iterator.next().getInt(); } return valueArray; }
public static List getProfilesWhoseBaseIs(String baseName, FormatProfiles profilesroot) { List results = new ArrayList(); EList profiles = profilesroot.getProfile(); for (Iterator it = profiles.iterator(); it.hasNext(); ) { Profile profile = (Profile) it.next(); String profileBase = profile.getBase(); if (profileBase != null && profileBase.equals(baseName)) results.add(profile); } return results; }
private static Control getControlByName(DefaultProfile defaultProfile, String controlName) { Controls controls = defaultProfile.getControls(); EList cntrls = controls.getControl(); for (Iterator it = cntrls.iterator(); it.hasNext(); ) { Control control = (Control) it.next(); String controlElemName = control.getName(); if (controlElemName != null && controlElemName.equals(controlName)) return control; } return null; }
/** * try to find the profile node within <egl:format_profiles>, whose name is profileName * * @param profileName * @param formatprofiles * @return - null if not found */ public static Profile findProfileByName(String profileName, FormatProfiles formatprofiles) { EList profiles = formatprofiles.getProfile(); for (Iterator it = profiles.iterator(); it.hasNext(); ) { Profile profile = (Profile) it.next(); if (profileName.equals(profile.getName())) { return profile; } } return null; }
/** * check for transitions from initstate * * @param initState * @return */ private boolean isLoneTransition(EObject initState) { Pageflow pageflow = (Pageflow) initState.eContainer(); EList transitions = pageflow.getTransitions(); for (Iterator iter = transitions.iterator(); iter.hasNext(); ) { Transition transition = (Transition) iter.next(); if (transition.getFromState().equals(initState)) { return false; } } return true; }
/** * Gets the top level navexpression model. * * @return */ public CCM getModel() { if (null == ccm) { EList l = resource.getContents(); Iterator i = l.iterator(); while (i.hasNext()) { Object o = i.next(); if (o instanceof CCM) ccm = (CCM) o; } } return ccm; }
public static Setting getPreferenceSettingByID( Profile profile, String categoryId, String prefId) { EList settings = profile.getSetting(); if (settings != null) { for (Iterator it = settings.iterator(); it.hasNext(); ) { Setting setting = (Setting) it.next(); if (categoryId.equals(setting.getCategory()) && prefId.equals(setting.getPref())) return setting; } } return null; }
protected static void filterMPEForLib(EList<MindPathEntry> list) { for (Iterator iterator = list.iterator(); iterator.hasNext(); ) { MindPathEntry mpe = (MindPathEntry) iterator.next(); if (mpe.getEntryKind() == MindPathKind.SOURCE) { iterator.remove(); } } MindPathEntryCustomImpl mpe = new MindPathEntryCustomImpl(); mpe.setEntryKind(MindPathKind.SOURCE); mpe.setName("."); list.add(mpe); }
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { ProjectRegistry registry = ProjectPlugin.getPlugin().getProjectRegistry(); List<Project> projects = registry.getProjects(); registry.getProjects().removeAll(projects); EList list = registry.eResource().getResourceSet().getResources(); Set<Resource> toRemove = new HashSet<Resource>(); for (Iterator iter = list.iterator(); iter.hasNext(); ) { Resource element = (Resource) iter.next(); if (element != registry.eResource()) { element.unload(); toRemove.add(element); } } project = registry.getDefaultProject(); file = new File(project.eResource().getURI().toFileString()); if (file.exists()) { if (file.isFile()) { file.delete(); File parent = file.getParentFile(); File[] files = parent.listFiles(); for (File file : files) { file.delete(); } parent.delete(); } file.delete(); } registry.eResource().getResourceSet().getResources().removeAll(toRemove); project = registry.getProject( FileLocator.toFileURL(Platform.getInstanceLocation().getURL()).getFile()); resource1 = MapTests.createGeoResource(UDIGTestUtil.createDefaultTestFeatures(type1Name, 4), false); Map map = MapTests.createNonDynamicMapAndRenderer(resource1, new Dimension(512, 512)); map.setName(firstMapName); map.getLayersInternal().get(0).setName(firstMapLayerName); resource2 = MapTests.createGeoResource(UDIGTestUtil.createDefaultTestFeatures(type2Name, 6), false); map = MapTests.createNonDynamicMapAndRenderer(resource2, new Dimension(512, 512)); map.setName(secondMapName); map.getLayersInternal().get(0).setName(secondMapLayerName); }
protected double sumMemoryActuals(ComponentInstance ci, boolean isROM) { try { double total = isROM ? GetProperties.getROMActualInKB(ci, 0.0) : GetProperties.getRAMActualInKB(ci, 0.0); EList subcis = ci.getComponentInstances(); for (Iterator it = subcis.iterator(); it.hasNext(); ) { ComponentInstance subci = (ComponentInstance) it.next(); total += sumMemoryActuals(subci, isROM); } return total; } catch (PropertyDoesNotApplyToHolderException e) { /* * Callers are allowed to be sloppy and not care if the property * actually applies to the category of the component instance 'ci' */ return 0.0; } }
@Override public void pruneDependencies() { final Iterator<java.util.Map.Entry<EObject, EList<IScriptDependency>>> eIterator = getDependencies().entrySet().iterator(); while (eIterator.hasNext()) { final java.util.Map.Entry<EObject, EList<IScriptDependency>> e = eIterator.next(); final EList<IScriptDependency> dList = e.getValue(); final Iterator<IScriptDependency> dIterator = dList.iterator(); while (dIterator.hasNext()) { final IScriptDependency d = dIterator.next(); if (!d.eIsSet(IScriptEnginePackage.Literals.SCRIPT_DEPENDENCY__EXPRESSIONS)) { dIterator.remove(); } } if (dList.isEmpty()) { e.getKey().eAdapters().remove(myDependencyAdapter); eIterator.remove(); } } }
/** * Builds the dependency for a method element. * * @param element A method element. */ private void buildDependency(MethodElement element) { if (element == null) { return; } try { PackageDependency dependency = buildDependencyFor(element); boolean isProcess = element instanceof ProcessComponent; EList elements = element.eContents(); if (elements != null) { for (Iterator it = elements.iterator(); it.hasNext(); ) { Object obj = it.next(); if (!(obj instanceof MethodElement)) { continue; } MethodElement methodElement = (MethodElement) obj; if (methodElement != null && !LibraryUtil.selectable(methodElement)) { buildDependencyFor(methodElement); } else if (isProcess && methodElement instanceof ProcessPackage) { for (Iterator itt = methodElement.eAllContents(); itt.hasNext(); ) { Object objj = itt.next(); if (objj instanceof MethodElement) { MethodElement m = (MethodElement) objj; if (!LibraryUtil.selectable(m)) { buildDependencyFor(m); } } } } } } dependency.setLoaded(true); } catch (Exception e) { if (debug) { e.printStackTrace(); } } }
@Override public String toString() { /* * Don't return a string with spaces in it becase this is used to * create a name for the object, and we cannot have spaces in our * name, or else it messes up the XML/XMI processing. */ final StringBuffer name = new StringBuffer(); EList ml = getCurrentModes(); for (Iterator it = ml.iterator(); it.hasNext(); ) { final ModeInstance mi = (ModeInstance) it.next(); final ComponentInstance ci = (ComponentInstance) mi.eContainer(); name.append(ci.getComponentInstancePath()); if (name.length() > 0) { name.append("."); } name.append(mi.getName()); if (it.hasNext()) { name.append("#"); } } return name.toString(); }
/** * Calculate bandwidth demand from rate & data size * * @param pci Port connection instance * @return */ protected double calcBandwidthKBytesps(ConnectionInstanceEnd cie) { double res = 0; // TODO-LW add other cases if (cie instanceof FeatureInstance) { FeatureInstance fi = (FeatureInstance) cie; double datasize = GetProperties.getSourceDataSize(fi, GetProperties.getKBUnitLiteral(fi)); double srcRate = getDataRate(fi, 0.0); if (srcRate == 0) { double period = GetProperties.getPeriodInSeconds(fi.getContainingComponentInstance(), 0); if (period == 0) return res; srcRate = 1 / GetProperties.getPeriodInSeconds(fi.getContainingComponentInstance(), 1); } res = datasize * srcRate; EList fil = fi.getFeatureInstances(); if (fil.size() > 0) { double subres = 0; for (Iterator it = fil.iterator(); it.hasNext(); ) { FeatureInstance sfi = (FeatureInstance) it.next(); subres = subres + calcBandwidthKBytesps(sfi); } if (subres > res) { if (res > 0) { errManager.warningSummary( fi, null, "Bandwidth of feature group ports " + subres + " exceeds feature group bandwidth " + res); } res = subres; } } } return res; }
@Ignore @Test public void testSaveAndLoad() throws Exception { EList list = project.eResource().getResourceSet().getResources(); for (Iterator iter = list.iterator(); iter.hasNext(); ) { Resource element = (Resource) iter.next(); try { element.save(null); } catch (Exception e) { } if (!element.getContents().contains(ProjectPlugin.getPlugin().getProjectRegistry())) element.unload(); } ResourceSet set = new ResourceSetImpl(); Project project = (Project) set.getResource(URI.createURI("file://" + file.getAbsolutePath()), true) .getAllContents() .next(); //$NON-NLS-1$ assertFalse(project.eIsProxy()); assertNotNull(project); int maps = 0; boolean foundFirstMap = false; boolean foundSecondMap = false; List resources = project.getElements(); for (Iterator iter = resources.iterator(); iter.hasNext(); ) { Map map = (Map) iter.next(); assertFalse(map.eIsProxy()); assertEquals(1, map.getLayersInternal().size()); assertNotNull(map.getLayersInternal().get(0).getGeoResources().get(0)); assertNotNull( map.getLayersInternal() .get(0) .getResource(FeatureSource.class, new NullProgressMonitor())); if (map.getName().equals(firstMapName)) { foundFirstMap = true; assertEquals(firstMapLayerName, map.getLayersInternal().get(0).getName()); FeatureSource<SimpleFeatureType, SimpleFeature> source = map.getLayersInternal().get(0).getResource(FeatureSource.class, null); assertEquals(4, source.getCount(Query.ALL)); assertEquals(firstMapLayerName, map.getLayersInternal().get(0).getName()); } if (map.getName().equals(secondMapName)) { foundSecondMap = true; assertEquals(secondMapLayerName, map.getLayersInternal().get(0).getName()); FeatureSource<SimpleFeatureType, SimpleFeature> source = map.getLayersInternal().get(0).getResource(FeatureSource.class, null); assertEquals(6, source.getCount(Query.ALL)); assertEquals(secondMapLayerName, map.getLayersInternal().get(0).getName()); } maps++; } assertEquals(2, maps); assertTrue(foundFirstMap); assertTrue(foundSecondMap); }
public CharSequence apply(ImportManager importManager) { JvmOperation cacheMethod = (JvmOperation) logicalContainerProvider.getLogicalContainer(createExtensionInfo.getCreateExpression()); StringBuilderBasedAppendable appendable = new StringBuilderBasedAppendable(importManager); JvmDeclaredType containerType = cacheMethod.getDeclaringType(); JvmTypeReference listType = typeReferences.getTypeForName(ArrayList.class, containerType); JvmTypeReference collectonLiterals = typeReferences.getTypeForName(CollectionLiterals.class, containerType); String cacheVarName = cacheField.getSimpleName(); String cacheKeyVarName = appendable.declareVariable("CacheKey", "_cacheKey"); appendable.append("final "); typeReferenceSerializer.serialize(listType, containerType, appendable); appendable.append(cacheKeyVarName).append(" = "); typeReferenceSerializer.serialize(collectonLiterals, containerType, appendable); appendable.append(".newArrayList("); EList<JvmFormalParameter> list = cacheMethod.getParameters(); for (Iterator<JvmFormalParameter> iterator = list.iterator(); iterator.hasNext(); ) { JvmFormalParameter jvmFormalParameter = iterator.next(); appendable.append(getVarName(jvmFormalParameter)); if (iterator.hasNext()) { appendable.append(", "); } } appendable.append(");"); // declare result variable JvmTypeReference returnType = typeProvider.getType(createExtensionInfo.getCreateExpression()); appendable.append("\nfinal "); typeReferenceSerializer.serialize(returnType, containerType, appendable); String resultVarName = "_result"; appendable.append(" ").append(resultVarName).append(";"); // open synchronize block appendable.append("\nsynchronized (").append(cacheVarName).append(") {"); appendable.increaseIndentation(); // if the cache contains the key return the previously created object. appendable .append("\nif (") .append(cacheVarName) .append(".containsKey(") .append(cacheKeyVarName) .append(")) {"); appendable.increaseIndentation(); appendable .append("\nreturn ") .append(cacheVarName) .append(".get(") .append(cacheKeyVarName) .append(");"); appendable.decreaseIndentation().append("\n}"); // execute the creation compiler.toJavaStatement(createExtensionInfo.getCreateExpression(), appendable, true); appendable.append("\n"); appendable.append(resultVarName).append(" = "); compiler.toJavaExpression(createExtensionInfo.getCreateExpression(), appendable); appendable.append(";"); // store the newly created object in the cache appendable .append("\n") .append(cacheVarName) .append(".put(") .append(cacheKeyVarName) .append(", ") .append(resultVarName) .append(");"); // close synchronize block appendable.decreaseIndentation(); appendable.append("\n}"); appendable .append("\n") .append(initializerMethod.getSimpleName()) .append("(") .append(resultVarName); for (JvmFormalParameter parameter : cacheMethod.getParameters()) { appendable.append(", ").append(parameter.getName()); } appendable.append(");"); // return the result appendable.append("\nreturn "); appendable.append(resultVarName).append(";"); return appendable.toString(); }
/* * (non-Javadoc) * @see org.jboss.tools.seam.internal.core.project.facet.SeamFacetAbstractInstallDelegate#configureFacesConfigXml(org.eclipse.core.resources.IProject, org.eclipse.core.runtime.IProgressMonitor, java.lang.String) */ @Override protected void configureFacesConfigXml( final IProject project, IProgressMonitor monitor, String webConfigName) { FacesConfigArtifactEdit facesConfigEdit = null; try { facesConfigEdit = FacesConfigArtifactEdit.getFacesConfigArtifactEditForWrite(project, webConfigName); FacesConfigType facesConfig = facesConfigEdit.getFacesConfig(); EList applications = facesConfig.getApplication(); ApplicationType applicationType = null; boolean applicationExists = false; if (applications.size() <= 0) { applicationType = FacesConfigFactory.eINSTANCE.createApplicationType(); } else { applicationType = (ApplicationType) applications.get(0); applicationExists = true; } boolean localeConfigExists = false; for (Iterator iterator = applications.iterator(); iterator.hasNext(); ) { ApplicationType application = (ApplicationType) iterator.next(); EList localeConfigs = application.getLocaleConfig(); if (!localeConfigs.isEmpty()) { localeConfigExists = true; break; } } if (!localeConfigExists) { LocaleConfigType locale = FacesConfigFactory.eINSTANCE.createLocaleConfigType(); DefaultLocaleType defaultLocale = FacesConfigFactory.eINSTANCE.createDefaultLocaleType(); defaultLocale.setTextContent("en"); locale.setDefaultLocale(defaultLocale); SupportedLocaleType supportedLocale = FacesConfigFactory.eINSTANCE.createSupportedLocaleType(); supportedLocale.setTextContent("bg"); locale.getSupportedLocale().add(supportedLocale); supportedLocale = FacesConfigFactory.eINSTANCE.createSupportedLocaleType(); supportedLocale.setTextContent("de"); locale.getSupportedLocale().add(supportedLocale); supportedLocale = FacesConfigFactory.eINSTANCE.createSupportedLocaleType(); supportedLocale.setTextContent("en"); locale.getSupportedLocale().add(supportedLocale); supportedLocale = FacesConfigFactory.eINSTANCE.createSupportedLocaleType(); supportedLocale.setTextContent("fr"); locale.getSupportedLocale().add(supportedLocale); supportedLocale = FacesConfigFactory.eINSTANCE.createSupportedLocaleType(); supportedLocale.setTextContent("tr"); locale.getSupportedLocale().add(supportedLocale); applicationType.getLocaleConfig().add(locale); } boolean viewHandlerExists = false; IDOMModel domModel = facesConfigEdit.getIDOMModel(); if (domModel != null) { Element facesConfigElement = domModel.getDocument().getDocumentElement(); if (facesConfigElement != null) { if (facesConfigElement.getAttribute("version").startsWith("1")) { for (Iterator iterator = applications.iterator(); iterator.hasNext(); ) { ApplicationType application = (ApplicationType) iterator.next(); EList viewHandlers = application.getViewHandler(); for (Iterator iterator2 = viewHandlers.iterator(); iterator2.hasNext(); ) { ViewHandlerType viewHandlerType = (ViewHandlerType) iterator2.next(); if ("com.sun.facelets.FaceletViewHandler" .equals(viewHandlerType.getTextContent().trim())) { viewHandlerExists = true; break; } } } } else { // Don't add facelet view handler for JSF 2 viewHandlerExists = true; } } } if (!viewHandlerExists) { ViewHandlerType viewHandler = FacesConfigFactory.eINSTANCE.createViewHandlerType(); viewHandler.setTextContent("com.sun.facelets.FaceletViewHandler"); applicationType.getViewHandler().add(viewHandler); } if (!applicationExists) { facesConfig.getApplication().add(applicationType); } facesConfigEdit.save(monitor); } finally { if (facesConfigEdit != null) { facesConfigEdit.dispose(); } } }
/** * This method looks for inconsistent views of connectors to delete in case the connector is * re-oriented. * * @param viewsToDestroy the set of views of messages to destroy * @return the list of {@link View} of the connectors to delete */ public static Set<View> addConnectorViewsToDestroy(Set<View> viewsToDestroy) { // for all the views to destroy, we have to classify them by their own connector, // then we have to verify for each connector that the set of messages (to destroy) on it are the // only messages that he contains // if yes, we have to add the view of the connector to list of views to destroy // the set connectors that are concerned by the deleted to the messages views Set<View> connectors = null; Set<View> newViewsToDestroy = new HashSet<View>(viewsToDestroy); // for all the messages to delete, search for their parent connector Iterator<?> it = viewsToDestroy.iterator(); while (it.hasNext()) { View msgView = (View) it.next(); if ((msgView instanceof DecorationNode) && (msgView.getElement() instanceof Message)) { if (msgView.eContainer() instanceof Connector) { if (connectors == null) { connectors = new HashSet<View>(); } connectors.add((View) msgView.eContainer()); } } } // Now the connectors set contains all the connectors that may have to be deleted // we have to check which connector have to be deleted if (connectors != null) { // for each connector we have to search for the set of its labels views to be destroyed Iterator<?> it1 = connectors.iterator(); while (it1.hasNext()) { View conView = (View) it1.next(); // Construct the list of viewsOfLabelsToDestroy Set<View> viewsOfLabelsToDestroy = null; Iterator<?> it2 = viewsToDestroy.iterator(); while (it2.hasNext()) { View msgView = (View) it2.next(); if ((msgView instanceof DecorationNode) && (msgView.getElement() instanceof Message)) { if ((msgView.eContainer() instanceof Connector) && (msgView.eContainer().equals(conView))) { if (viewsOfLabelsToDestroy == null) { viewsOfLabelsToDestroy = new HashSet<View>(); } viewsOfLabelsToDestroy.add(msgView); } } } // if the set of viewsOfLabelsToDestroy contains all the real children of the connector // then add the connector to the views to destroy @SuppressWarnings("unchecked") EList<View> conChildren = conView.getChildren(); Set<View> comparisonResult = new HashSet<View>(conChildren.size()); for (Iterator<?> i = conChildren.iterator(); i.hasNext(); ) { View element = (View) i.next(); if ((element instanceof DecorationNode) && (element.getElement() instanceof Message)) { if (!viewsOfLabelsToDestroy.contains(element)) { comparisonResult.add(element); } } } if (comparisonResult .isEmpty()) { // the set of viewsOfLabelsToDestroy contains all the real children of the // connector newViewsToDestroy.add(conView); } } } return newViewsToDestroy; }
/** * check the load from components bound to the given processor The components can be threads or * higher level components. * * @param curProcessor Component Instance of processor */ protected void checkProcessorLoad(ComponentInstance curProcessor, final SystemOperationMode som) { boolean isCPUActive; if (curProcessor.getSubcomponent().getAllInModes().size() == 0) { isCPUActive = true; } else { isCPUActive = false; for (Mode mi : curProcessor.getSubcomponent().getAllInModes()) { // OsateDebug.osateDebug("somName=" + somName + " mi=" + mi); if (som.getName().equalsIgnoreCase(mi.getName())) { // OsateDebug.osateDebug("cpu " + curProcessor.getName() + "is active for mode" + // somName); isCPUActive = true; } } } if (isCPUActive == false) { return; } UnitLiteral mipsliteral = GetProperties.getMIPSUnitLiteral(curProcessor); double MIPScapacity = GetProperties.getMIPSCapacityInMIPS(curProcessor, 0.0); if (MIPScapacity == 0 && InstanceModelUtil.isVirtualProcessor(curProcessor)) { MIPScapacity = GetProperties.getMIPSBudgetInMIPS(curProcessor); } long timeBefore = System.currentTimeMillis(); OsateDebug.osateDebug( "[CPU] before get sw comps (CPU=" + curProcessor.getName() + ",cat=" + curProcessor.getComponentClassifier().getCategory().getName() + ")"); EList<ComponentInstance> boundComponents = InstanceModelUtil.getBoundSWComponents(curProcessor); long timeAfter = System.currentTimeMillis(); long period = timeAfter - timeBefore; OsateDebug.osateDebug("[CPU] after get sw comps, time taken=" + period + "ms"); if (boundComponents.size() == 0 && MIPScapacity > 0) { errManager.infoSummary( curProcessor, som.getName(), "No application components bound to " + curProcessor.getComponentInstancePath() + " with MIPS capacity " + GetProperties.toStringScaled(MIPScapacity, mipsliteral)); return; } if (MIPScapacity == 0 && InstanceModelUtil.isVirtualProcessor(curProcessor)) { errManager.warningSummary( curProcessor, som.getName(), "Virtual processor " + curProcessor.getComponentInstancePath() + " has no MIPS capacity or budget."); return; } if (MIPScapacity == 0 && InstanceModelUtil.isProcessor(curProcessor)) { errManager.errorSummary( curProcessor, som.getName(), "Processor " + curProcessor.getComponentInstancePath() + " has no MIPS capacity but has bound components."); } if (InstanceModelUtil.isVirtualProcessor(curProcessor)) { logHeader( "\n\nDetailed Workload Report for Virtual Processor " + curProcessor.getComponentInstancePath() + " with Capacity " + GetProperties.toStringScaled(MIPScapacity, mipsliteral) + "\n\nComponent,Budget,Actual"); } else { logHeader( "\n\nDetailed Workload Report for Processor " + curProcessor.getComponentInstancePath() + " with Capacity " + GetProperties.toStringScaled(MIPScapacity, mipsliteral) + "\n\nComponent,Budget,Actual"); } double totalMIPS = 0.0; for (Iterator<ComponentInstance> it = boundComponents.iterator(); it.hasNext(); ) { ComponentInstance bci = (ComponentInstance) it.next(); boolean isComponentActive; if ((som == null) || (bci.getSubcomponent().getAllInModes().size() == 0)) { isComponentActive = true; } else { isComponentActive = false; for (Mode mi : bci.getSubcomponent().getAllInModes()) { // OsateDebug.osateDebug("somName=" + somName + " mi=" + mi); if (som.getName().equalsIgnoreCase(mi.getName())) { // OsateDebug.osateDebug("cpu " + curProcessor.getName() + "is active for mode" + // somName); isComponentActive = true; } } } if (isComponentActive == true) { double actualmips = sumBudgets(bci, ResourceKind.MIPS, mipsliteral, true, som, ""); totalMIPS += actualmips; } } logHeader("Total," + GetProperties.toStringScaled(totalMIPS, mipsliteral)); if (totalMIPS > MIPScapacity) { errManager.errorSummary( curProcessor, som.getName(), "Total MIPS " + GetProperties.toStringScaled(totalMIPS, mipsliteral) + " of bound tasks exceeds MIPS capacity " + GetProperties.toStringScaled(MIPScapacity, mipsliteral) + " of " + curProcessor.getComponentInstancePath()); } else if (totalMIPS == 0.0) { errManager.warningSummary(curProcessor, som.getName(), "Bound app's have no MIPS budget."); } else { errManager.infoSummary( curProcessor, som.getName(), "Total MIPS " + GetProperties.toStringScaled(totalMIPS, mipsliteral) + " of bound tasks within " + "MIPS capacity " + GetProperties.toStringScaled(MIPScapacity, mipsliteral) + " of " + curProcessor.getComponentInstancePath()); } }
/** * get the list of command to put an eobject before or after another EObject It will look for the * good role of the child eobject * * @param domain the Transactional Domain, cannot be null * @param targetOwner the eobject that will contain the drop object , cannot be null * @param objectLocation the object where we want to drop the object * @param newElement that we want to move, cannot be null * @return the list of commands to to the drop */ protected List<Command> getOrderChangeCommand( TransactionalEditingDomain domain, EObject targetOwner, EObject objectLocation, EObject newElement, boolean before) { ArrayList<Command> commandList = new ArrayList<Command>(); ArrayList<EStructuralFeature> possibleEFeatures = new ArrayList<EStructuralFeature>(); EList<EStructuralFeature> featureList = targetOwner.eClass().getEAllStructuralFeatures(); // Abort when trying to change order moving the element in one of its children if (EcoreUtil.isAncestor(newElement, targetOwner)) { return Collections.emptyList(); } // find the feature between childreen and owner Iterator<EStructuralFeature> iterator = featureList.iterator(); while (iterator.hasNext()) { EStructuralFeature eStructuralFeature = (EStructuralFeature) iterator.next(); if (eStructuralFeature instanceof EReference) { EReference ref = (EReference) eStructuralFeature; if (ref.isContainment()) { if (isSubClass(ref.getEType(), newElement.eClass())) { possibleEFeatures.add(eStructuralFeature); } } } } // create the command Iterator<EStructuralFeature> iteratorFeature = possibleEFeatures.iterator(); while (iteratorFeature.hasNext()) { EStructuralFeature eStructuralFeature = (EStructuralFeature) iteratorFeature.next(); ArrayList<EObject> tmp = new ArrayList<EObject>(); if (targetOwner.eGet(eStructuralFeature) instanceof Collection<?>) { // get all element of this efeature tmp.addAll((Collection<EObject>) targetOwner.eGet(eStructuralFeature)); if (!newElement.equals(objectLocation)) { tmp.remove(newElement); // normally tmp.indexOf(objectLocation)!= -1 // if this the case objectlocation=new element and // it has been removed int indexObject = tmp.indexOf(objectLocation); if (before && indexObject != -1) { tmp.add(tmp.indexOf(objectLocation), newElement); } else if (!before && indexObject != -1) { tmp.add(tmp.indexOf(objectLocation) + 1, newElement); } } } else { tmp.add(newElement); } SetRequest setRequest = new SetRequest(targetOwner, eStructuralFeature, tmp); IElementEditService provider = ElementEditServiceUtils.getCommandProvider(targetOwner); if (provider != null) { // Retrieve delete command from the Element Edit service ICommand command = provider.getEditCommand(setRequest); if (command != null) { commandList.add(new GMFtoEMFCommandWrapper(command)); } } } return commandList; }
/** * _step Do the step for a single thread * * @param time * @param timeDelta * @param cycle * @param threadnum */ protected void _step(STEMTime time, long timeDelta, int cycle, short threadnum) { // this.setProgress(0.0); // We only deal with standard disease model decorators ArrayList<Decorator> iDecorators = new ArrayList<Decorator>(); for (Decorator d : getDecorators()) { if (d instanceof IntegrationDecorator) iDecorators.add(d); } // First we get the step size, either the default step size // (initially 1.0) or the last step size used. double h = this.getStepSize(); // x is to keep track of how far we have advanced in the solution. It is essentially // a double cycle representation double x = this.getCurrentX(); // Substantial performance can be gained here. Basically if the current cycle // is greater than the cycle requested by the simulation, we are done. This // means that the error tolerance between last step and this step is small // enough so we don't need to update the labels. The error tolerance is // specified in the disease model // *** OBSERVE: Since we limit h to max 1 below, this code is never invoked. It's kept // *** around in case we want to allow time to be calculated far out in the future if // *** the error is small enough if (x >= cycle) { // Just copy the next value the same as the current value for all labels for (Decorator sdm : iDecorators) { EList<DynamicLabel> myLabels = sdm.getLabelsToUpdate(threadnum, num_threads); int numLabels = myLabels.size(); double n = 0.0; int setProgressEveryNthNode = num_threads * numLabels / (MAX_PROGRESS_REPORTS); if (setProgressEveryNthNode == 0) setProgressEveryNthNode = 1; for (final Iterator<DynamicLabel> currentStateLabelIter = myLabels.iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); // The estimated disease value contains the value calculated at position x IntegrationLabelValue nextValueAtX = (IntegrationLabelValue) EcoreUtil.copy(diseaseLabel.getProbeValue()); IntegrationLabelValue currentValueAtCycle = (IntegrationLabelValue) diseaseLabel.getCurrentValue(); IntegrationLabelValue nextState = (IntegrationLabelValue) diseaseLabel.getNextValue(); adjustValuesToCycle(currentValueAtCycle, nextValueAtX, x, cycle); // NextValueAtX has been modified here to the correct value for this cycle. nextState.set(nextValueAtX); // The next value is valid now. diseaseLabel.setNextValueValid(true); double progress = n / numLabels; jobs[threadnum].setProgress(progress); if (n % setProgressEveryNthNode == 0) { // Get the progress for all threads for (int i = 0; i < num_threads; ++i) if (i != threadnum && jobs[i] != null) progress += jobs[i].getProgress(); progress /= num_threads; sdm.setProgress(progress); } n += 1.0; } } // For each decorator // So that validation code above is happy jobs[threadnum].h = h; jobs[threadnum].t = x; return; } // When x (or time) is this we're done double end = Math.floor(this.getCurrentX()) + 1.0; // Make sure we actually have labels to update boolean workToDo = false; for (Decorator sdm : iDecorators) if (sdm.getLabelsToUpdate(threadnum, num_threads).size() > 0) { workToDo = true; break; } if (!workToDo) { // Nothing to do, just advance x and set h jobs[threadnum].h = h; jobs[threadnum].t = x; // Be nice and walk in step with others until done while (x < end) { try { // Set to a large number to make sure it's larger than any step size reported // by another thread do { jobs[threadnum].h = Double.MAX_VALUE; stepSizeBarrier.await(); } while (this.maximumError > 1.0); updateDoneBarrier.await(); } catch (InterruptedException ie) { // Should never happen Activator.logError(ie.getMessage(), ie); } catch (BrokenBarrierException bbe) { // Should never happen Activator.logError(bbe.getMessage(), bbe); } // Set to the smallest value reported by another thread h = this.smallestH; x += h; jobs[threadnum].h = h; jobs[threadnum].t = x; } return; } // We use the Runge Kutta Kash Carp method to advance to the next // step in the simulation. Two estimates of the disease deltas // are calculated and compared to each other. If they differ // by more than a maximum error (determined by a parameter for // the disease model), we reduce the step size until an acceptable // error is reached. // These are used during Runge Kutta calculations: Map<IntegrationLabel, IntegrationLabelValue> k1map = new HashMap<IntegrationLabel, IntegrationLabelValue>(); Map<IntegrationLabel, IntegrationLabelValue> k2map = new HashMap<IntegrationLabel, IntegrationLabelValue>(); Map<IntegrationLabel, IntegrationLabelValue> k3map = new HashMap<IntegrationLabel, IntegrationLabelValue>(); Map<IntegrationLabel, IntegrationLabelValue> k4map = new HashMap<IntegrationLabel, IntegrationLabelValue>(); Map<IntegrationLabel, IntegrationLabelValue> k5map = new HashMap<IntegrationLabel, IntegrationLabelValue>(); Map<IntegrationLabel, IntegrationLabelValue> k6map = new HashMap<IntegrationLabel, IntegrationLabelValue>(); // Used below as temporary place holder, one for each decorator IntegrationLabelValue _k1[], _k2[], _k3[], _k4[], _k5[], _k6[]; int numDecorators = iDecorators.size(); _k1 = new IntegrationLabelValue[numDecorators]; _k2 = new IntegrationLabelValue[numDecorators]; _k3 = new IntegrationLabelValue[numDecorators]; _k4 = new IntegrationLabelValue[numDecorators]; _k5 = new IntegrationLabelValue[numDecorators]; _k6 = new IntegrationLabelValue[numDecorators]; // The final estimates for label values are stored here Map<IntegrationLabel, IntegrationLabelValue> finalEstimate = new HashMap<IntegrationLabel, IntegrationLabelValue>(); // Delta is used to scale the step (h) double delta = 0.0; int n = 0; for (Decorator sdm : iDecorators) { Iterator<DynamicLabel> iter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); IntegrationLabel firstLabel = (IntegrationLabel) iter.next(); // Initialize temporary place holders just by creating dups of the first label available _k1[n] = (IntegrationLabelValue) EcoreUtil.copy(firstLabel.getCurrentValue()); _k2[n] = (IntegrationLabelValue) EcoreUtil.copy(firstLabel.getCurrentValue()); _k3[n] = (IntegrationLabelValue) EcoreUtil.copy(firstLabel.getCurrentValue()); _k4[n] = (IntegrationLabelValue) EcoreUtil.copy(firstLabel.getCurrentValue()); _k5[n] = (IntegrationLabelValue) EcoreUtil.copy(firstLabel.getCurrentValue()); _k6[n++] = (IntegrationLabelValue) EcoreUtil.copy(firstLabel.getCurrentValue()); } // Keep track if whether anyone want to stop // or pause updating labels boolean interrupt = false, pause = false; // We keep these around to determine when to call setProgress(...) on the decorators. // If we call too frequently we can too many callbacks which affects performance. double nextProgressReportStep = num_threads * (end - x) / MAX_PROGRESS_REPORTS; double nextProgressReport = x + nextProgressReportStep; // HashMap<StandardDiseaseModelLabel, StandardDiseaseModelLabelValue> validate = new // HashMap<StandardDiseaseModelLabel, StandardDiseaseModelLabelValue>(); // This is the main loop we keep iterating over until we are done with the step while (x < end) { k1map.clear(); k2map.clear(); k3map.clear(); k4map.clear(); k5map.clear(); k6map.clear(); finalEstimate.clear(); // Validation code kept here if needed in the future /* HashMap<StandardDiseaseModelLabel, StandardDiseaseModelLabelValue> validate = new HashMap<StandardDiseaseModelLabel, StandardDiseaseModelLabelValue>(); if(!redo) for(StandardDiseaseModelImpl sdm:diseaseModelDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads) .iterator(); currentStateLabelIter.hasNext();) { final StandardDiseaseModelLabel diseaseLabel = (StandardDiseaseModelLabel) currentStateLabelIter .next(); final StandardDiseaseModelLabelValue val = (StandardDiseaseModelLabelValue)diseaseLabel.getCurrentDiseaseModelTempLabelValue(); validate.put(diseaseLabel, val); } } else { for(StandardDiseaseModelImpl sdm:diseaseModelDecorators) for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads) .iterator(); currentStateLabelIter.hasNext();) { final StandardDiseaseModelLabel diseaseLabel = (StandardDiseaseModelLabel) currentStateLabelIter .next(); final SIRLabelValue val = (SIRLabelValue)diseaseLabel.getCurrentDiseaseModelTempLabelValue(); validate.put(diseaseLabel, val); final SIRLabelValue oldVal = (SIRLabelValue)validate.get(diseaseLabel); if(val.getI() != oldVal.getI() || val.getS() != oldVal.getS() || val.getR() != oldVal.getR() || //val.getE() != oldVal.getE() || val.getBirths() != oldVal.getBirths() || val.getDeaths() != oldVal.getDeaths() || val.getDiseaseDeaths() != oldVal.getDiseaseDeaths() ) Activator.logError("Error, old and new value not the same label: "+diseaseLabel, new Exception()); } } */ // ToDo: We should check if a maximum number of iterations have been // exceeded here and throw an error. // First, get the delta values at the current state for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .calculateDelta(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .applyExternalDeltas(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); // Set the scaling factor for disease parameters for each decorator and location for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); IntegrationLabelValue scale = (IntegrationLabelValue) diseaseLabel.getErrorScale(); scale.set((IntegrationLabelValue) diseaseLabel.getTempValue()); IntegrationLabelValue dt = (IntegrationLabelValue) EcoreUtil.copy(diseaseLabel.getDeltaValue()); dt.scale(h); dt.abs(); dt.add(TINY); scale.abs(); scale.add(dt); } } // Step 1 in Runge Kutta Fehlberg. // Get the delta values out of each node label and // build a first estimate of the next value' for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); IntegrationLabelValue deltaLabel = (IntegrationLabelValue) diseaseLabel.getDeltaValue(); k1map.put(diseaseLabel, (IntegrationLabelValue) EcoreUtil.copy(deltaLabel)); deltaLabel.scale(h); deltaLabel.scale(b21); ((IntegrationLabelValue) diseaseLabel.getProbeValue()) .set(deltaLabel.add((IntegrationLabelValue) diseaseLabel.getTempValue())); } } // Now get the next delta values for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .calculateDelta(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .applyExternalDeltas(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); // Step 2 in Runge Kutta Fehlberg. // Get the delta values out of each node label and // build a second estimate of the next value n = 0; for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); IntegrationLabelValue deltaLabel = (IntegrationLabelValue) diseaseLabel.getDeltaValue(); k2map.put(diseaseLabel, (IntegrationLabelValue) EcoreUtil.copy(deltaLabel)); _k1[n].set(k1map.get(diseaseLabel)); _k2[n].set(deltaLabel); IntegrationLabelValue estDelta = _k1[n].scale(b31); _k2[n].scale(b32); estDelta.add(_k2[n]); estDelta.scale(h); ((IntegrationLabelValue) diseaseLabel.getProbeValue()) .set(estDelta.add((IntegrationLabelValue) diseaseLabel.getTempValue())); } ++n; } // Now get the next delta values for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .calculateDelta(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .applyExternalDeltas(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); // Step 3 in Runge Kutta Fehlberg. // Get the delta values out of each node label and // build a third estimate of the next value n = 0; for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); IntegrationLabelValue deltaLabel = (IntegrationLabelValue) diseaseLabel.getDeltaValue(); k3map.put(diseaseLabel, (IntegrationLabelValue) EcoreUtil.copy(deltaLabel)); _k1[n].set(k1map.get(diseaseLabel)); _k2[n].set(k2map.get(diseaseLabel)); _k3[n].set(deltaLabel); _k1[n].scale(b41); _k2[n].scale(b42); _k3[n].scale(b43); IntegrationLabelValue estDelta = _k1[n]; estDelta.add(_k2[n]); estDelta.add(_k3[n]); estDelta.scale(h); ((IntegrationLabelValue) diseaseLabel.getProbeValue()) .set(estDelta.add((IntegrationLabelValue) diseaseLabel.getTempValue())); } ++n; } // Now get the next delta values for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .calculateDelta(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .applyExternalDeltas(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); // Step 4 in Runge Kutta Fehlberg. // Get the delta values out of each node label and // build a fourth estimate of the next value n = 0; for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); IntegrationLabelValue deltaLabel = (IntegrationLabelValue) diseaseLabel.getDeltaValue(); k4map.put(diseaseLabel, (IntegrationLabelValue) EcoreUtil.copy(deltaLabel)); _k1[n].set(k1map.get(diseaseLabel)); _k2[n].set(k2map.get(diseaseLabel)); _k3[n].set(k3map.get(diseaseLabel)); _k4[n].set(deltaLabel); _k1[n].scale(b51); _k2[n].scale(b52); _k3[n].scale(b53); _k4[n].scale(b54); IntegrationLabelValue estDelta = _k1[n]; estDelta.add(_k2[n]); estDelta.add(_k3[n]); estDelta.add(_k4[n]); estDelta.scale(h); ((IntegrationLabelValue) diseaseLabel.getProbeValue()) .set(estDelta.add((IntegrationLabelValue) diseaseLabel.getTempValue())); } ++n; } // Now get the next delta values for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .calculateDelta(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .applyExternalDeltas(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); // Step 5 in Runge Kutta Fehlberg. // Get the delta values out of each node label and // build a fifth estimate of the next value n = 0; for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); IntegrationLabelValue deltaLabel = (IntegrationLabelValue) diseaseLabel.getDeltaValue(); k5map.put(diseaseLabel, (IntegrationLabelValue) EcoreUtil.copy(deltaLabel)); _k1[n].set(k1map.get(diseaseLabel)); _k2[n].set(k2map.get(diseaseLabel)); _k3[n].set(k3map.get(diseaseLabel)); _k4[n].set(k4map.get(diseaseLabel)); _k5[n].set(deltaLabel); _k1[n].scale(b61); _k2[n].scale(b62); _k3[n].scale(b63); _k4[n].scale(b64); _k5[n].scale(b65); IntegrationLabelValue estDelta = _k1[n]; estDelta.add(_k2[n]); estDelta.add(_k3[n]); estDelta.add(_k4[n]); estDelta.add(_k5[n]); estDelta.scale(h); ((IntegrationLabelValue) diseaseLabel.getProbeValue()) .set(estDelta.add((IntegrationLabelValue) diseaseLabel.getTempValue())); } ++n; } // Now get the next delta values for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .calculateDelta(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); for (Decorator sdm : iDecorators) ((IntegrationDecorator) sdm) .applyExternalDeltas(time, timeDelta, sdm.getLabelsToUpdate(threadnum, num_threads)); // Step 6 in Runge Kutta Fehlberg. // Calculate k6 n = 0; for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); IntegrationLabelValue deltaLabel = (IntegrationLabelValue) diseaseLabel.getDeltaValue(); k6map.put(diseaseLabel, (IntegrationLabelValue) EcoreUtil.copy(deltaLabel)); } ++n; } // Step 7 in Runge Kutta Fehlberg // Calculate the two estimates from k1, .. k6 values // and determine the maximum difference (error) between them. boolean success = true; // Were we able to update all labels without a large enough error? double maxerror = 0.0; n = 0; for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); IntegrationLabelValue currentValue = (IntegrationLabelValue) diseaseLabel.getTempValue(); _k1[n].set(k1map.get(diseaseLabel)); _k3[n].set(k3map.get(diseaseLabel)); _k4[n].set(k4map.get(diseaseLabel)); _k5[n].set(k5map.get(diseaseLabel)); _k6[n].set(k6map.get(diseaseLabel)); _k1[n].scale(c1); _k3[n].scale(c3); _k4[n].scale(c4); _k6[n].scale(c6); // New Y IntegrationLabelValue yout = (IntegrationLabelValue) EcoreUtil.copy(_k1[n].add(_k3[n]).add(_k4[n]).add(_k6[n])); yout.scale(h); yout.add(currentValue); // Get the error _k1[n].set(k1map.get(diseaseLabel)); _k3[n].set(k3map.get(diseaseLabel)); _k4[n].set(k4map.get(diseaseLabel)); _k5[n].set(k5map.get(diseaseLabel)); _k6[n].set(k6map.get(diseaseLabel)); _k1[n].scale(dc1); _k3[n].scale(dc3); _k4[n].scale(dc4); _k5[n].scale(dc5); _k6[n].scale(dc6); IntegrationLabelValue yerror = (IntegrationLabelValue) EcoreUtil.copy(_k1[n].add(_k3[n]).add(_k4[n]).add(_k5[n]).add(_k6[n])); yerror.scale(h); yerror.divide((IntegrationLabelValue) diseaseLabel.getErrorScale()); double error = yerror.max(); error /= relativeTolerance; if (error > maxerror) { maxerror = error; } if (error <= 1.0) finalEstimate.put(diseaseLabel, (IntegrationLabelValue) EcoreUtil.copy(yout)); } ++n; } jobs[threadnum].h = h; jobs[threadnum].maxerror = maxerror; try { stepSizeBarrier.await(); } catch (InterruptedException ie) { // Should never happen Activator.logError(ie.getMessage(), ie); } catch (BrokenBarrierException bbe) { // Should never happen Activator.logError(bbe.getMessage(), bbe); } // At least one of the threads had to large of an error, fail if (this.maximumError > 1.0) success = false; // Are we done? if (success) { // Check to make sure if (this.smallestH > h) Activator.logError( "Error, h was less than the smallest, perhaps barrier process failed to execute? h:" + h + " vs " + this.smallestH, new Exception()); // Yes, hurrah, advance x using the step size h x += h; if (this.maximumError > ERRCON) h = SAFETY * h * Math.pow(this.maximumError, PGROW); else h = 5.0 * h; // Limit to max 1 if (h > 1.0) h = 1.0; // Make sure we don't overshoot if (x < end && x + h > end) h = (end - x); // Update the current value to the new position for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); ((IntegrationLabelValue) diseaseLabel.getTempValue()) .set(finalEstimate.get(diseaseLabel)); ((IntegrationLabelValue) diseaseLabel.getProbeValue()) .set(finalEstimate.get(diseaseLabel)); } } // Wait until all other threads have updated the current value try { updateDoneBarrier.await(); } catch (InterruptedException ie) { // Should never happen Activator.logError(ie.getMessage(), ie); } catch (BrokenBarrierException bbe) { // Should never happen Activator.logError(bbe.getMessage(), bbe); } double progress = (end - x < 0.0) ? 1.0 : 1.0 - (end - x); jobs[threadnum].setProgress(progress); if (x > nextProgressReport) { // Get the progress for all threads for (int i = 0; i < num_threads; ++i) if (i != threadnum && jobs[i] != null) progress += jobs[i].getProgress(); progress /= num_threads; for (Decorator sdm : iDecorators) sdm.setProgress(progress); nextProgressReport += nextProgressReportStep; } } else { // At least one thread failed, change the step size // Problem, error too big, we need to reduce the step size delta = SAFETY * h * Math.pow(this.maximumError, PSHRNK); if (h > 0.0) h = (delta > 0.1 * h) ? delta : 0.1 * h; else h = (delta > 0.1 * h) ? 0.1 * h : delta; // We didn't succeed. // Reset the estimated value back to the original, the step size // has been reduced so we well try again. // Set the estimated value back to the current original value for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); ((IntegrationLabelValue) diseaseLabel.getProbeValue()) .set((IntegrationLabelValue) diseaseLabel.getTempValue()); } } } } // While x < end jobs[threadnum].t = x; jobs[threadnum].h = h; // Remember the step size and position in the solver this.setStepSize(h); this.setCurrentX(x); // We're done for (Decorator sdm : iDecorators) { for (final Iterator<DynamicLabel> currentStateLabelIter = sdm.getLabelsToUpdate(threadnum, num_threads).iterator(); currentStateLabelIter.hasNext(); ) { final IntegrationLabel diseaseLabel = (IntegrationLabel) currentStateLabelIter.next(); // This is the next state for the label IntegrationLabelValue nextState = (IntegrationLabelValue) diseaseLabel.getNextValue(); // This is the original current state at the previous cycle IntegrationLabelValue originalState = (IntegrationLabelValue) diseaseLabel.getCurrentValue(); // This is the final value calculated at position x. IntegrationLabelValue newValue = finalEstimate.get(diseaseLabel); // x could be larger than the requested cycle, so we do a linear interpolation // to fit it exactly to the requested cycle // *** Not needed since we always end exactly at the requested cycle // adjustValuesToCycle(originalState, newValue, x, cycle); // New value has been modified here to fit the requested cycle nextState.set(newValue); // Do any model specific work for instance add noise ((IntegrationDecorator) sdm).doModelSpecificAdjustments((LabelValue) nextState); // The next value is valid now. diseaseLabel.setNextValueValid(true); } } }
/** * * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated NOT */ @Override public boolean step(STEMTime time, long timeDelta, int cycle) { // Validate all decorators that return deltas to make sure // they are of deterministic nature. The Runge Kutta integratio // can only handle determininistic variants for (Decorator decorator : this.getDecorators()) if (decorator instanceof IntegrationDecorator) { IntegrationDecorator idec = (IntegrationDecorator) decorator; if (!idec.isDeterministic()) { Activator.logError( "Error, decorator: " + idec + " is not deterministic. The Runge Kutta Integrator can only handle deterministic models.", new Exception()); return false; } } Activator act = org.eclipse.stem.ui.Activator.getDefault(); if (act != null) { final Preferences preferences = act.getPluginPreferences(); num_threads = (short) preferences.getInt( org.eclipse.stem.ui.preferences.PreferenceConstants.SIMULATION_THREADS); } else num_threads = 2; // Just so we can run inside junit test final int c = cycle; // Initialize latches stepSizeBarrier = new CyclicBarrier( num_threads, new Runnable() { public void run() { // All threads successfully advanced time by some step h. // Find the smallest smallestH = Double.MAX_VALUE; maximumError = -Double.MAX_VALUE; for (int i = 0; i < num_threads; ++i) { if (jobs[i].h <= smallestH) { if (maximumError < jobs[i].maxerror) maximumError = jobs[i].maxerror; smallestH = jobs[i].h; } } } }); updateDoneBarrier = new CyclicBarrier(num_threads); // Find triggers and make sure they are invoked for (Decorator decorator : this.getDecorators()) { if (decorator instanceof Trigger) { decorator.updateLabels(time, timeDelta, cycle); } } // First initialize the probe and temp label values from the current // label values. for (Decorator decorator : this.getDecorators()) { EList<DynamicLabel> allLabels = decorator.getLabelsToUpdate(); for (final Iterator<DynamicLabel> currentStateLabelIter = allLabels.iterator(); currentStateLabelIter.hasNext(); ) { if (decorator instanceof IntegrationDecorator) { // It's a standard disease model with a standard disease model label final IntegrationLabel iLabel = (IntegrationLabel) currentStateLabelIter.next(); ((IntegrationLabelValue) iLabel.getProbeValue()) .set((IntegrationLabelValue) iLabel.getCurrentValue()); ((IntegrationLabelValue) iLabel.getTempValue()) .set((IntegrationLabelValue) iLabel.getCurrentValue()); ((IntegrationLabelValue) iLabel.getTempValue()).prepareCycle(); ((IntegrationLabelValue) iLabel.getProbeValue()).prepareCycle(); } else currentStateLabelIter.next(); } } if (jobs == null || jobs.length != num_threads) { // Initialize the jobs if not done yet or of the number of threads changes jobs = new RkJob[num_threads]; for (short i = 0; i < num_threads; ++i) { final short threadnum = i; jobs[i] = new RkJob("Worker " + i, threadnum, this); } // For each job } // If not initialized // Initialize int thread = 0; for (RkJob j : jobs) { j.cycle = c; j.time = time; j.timeDelta = timeDelta; } // Schedule. Jobs can be rescheduled after finished for (RkJob j : jobs) j.schedule(); // Wait until all jobs completed for (RkJob j : jobs) { try { j.join(); } catch (InterruptedException ie) { Activator.logError(ie.getMessage(), ie); } } // Set the common time and step size here and validate everything is right double minStep = Double.MAX_VALUE; double currentT = jobs[0].t; for (RkJob j : jobs) { // The jobs have calculated new step sizes after they finished. Pick the // smallest one for the next cycle if (j.h < minStep) minStep = j.h; if (j.t != currentT) Activator.logError( "Error, one thread was in misstep with other threads, its time was " + j.t + " versus " + currentT, new Exception()); } return true; }
/** * check the load from components bound to the given memory The components can be threads or * higher level components. * * @param curMemory Component Instance of memory */ protected void doMemoryLoad( ComponentInstance curMemory, String somName, EList boundComponents, boolean isROM) { double totalMemory = 0.0; UnitLiteral kbliteral = GetProperties.getKBUnitLiteral(curMemory); String resourceName = isROM ? "ROM" : "RAM"; double Memorycapacity = isROM ? GetProperties.getROMCapacityInKB(curMemory, 0.0) : GetProperties.getRAMCapacityInKB(curMemory, 0.0); if (boundComponents.size() == 0 && Memorycapacity > 0) { errManager.infoSummary( curMemory, somName, "No application components bound to " + curMemory.getComponentInstancePath() + " with " + resourceName + " capacity " + GetProperties.toStringScaled(Memorycapacity, kbliteral)); return; } if (Memorycapacity == 0) { errManager.errorSummary( curMemory, somName, "Memory " + curMemory.getComponentInstancePath() + " has no " + resourceName + " capacity but has bound components."); } logHeader( "\n\nDetailed Workload Report for memory " + curMemory.getComponentInstancePath() + " with Capacity " + GetProperties.toStringScaled(Memorycapacity, kbliteral) + "\n\nComponent,Budget,Actual"); Set budgeted = new HashSet(); for (Iterator it = boundComponents.iterator(); it.hasNext(); ) { String notes = ""; ComponentInstance bci = (ComponentInstance) it.next(); double totalactual = sumMemoryActuals(bci, isROM); double budget = isROM ? GetProperties.getROMBudgetInKB(bci, 0.0) : GetProperties.getRAMBudgetInKB(bci, 0.0); if (totalactual > 0) { // only compare if there were actuals if (totalactual > budget) { notes = notes + ",Error: " + resourceName + " subtotal exceeds budget by " + (totalactual - budget) + " KB"; } else if (totalactual < budget) { notes = notes + ",Warning: " + resourceName + " Subtotal under budget by " + (budget - totalactual) + " KB"; } } if (totalactual == 0.0) { // we use a budget number as there are no actuals if (budget > 0 && !budgeted.contains(bci)) { // only add it if no children budget numbers have been added totalMemory += budget; detailedLog(bci, budget, kbliteral); // add ancestors to budgeted list so their budget does not get added later while ((bci = bci.getContainingComponentInstance()) != null) { budgeted.add(bci); } } } else { // add only the current actual; the children actual have been added before double currentActual = isROM ? GetProperties.getROMActualInKB(bci, 0.0) : GetProperties.getRAMActualInKB(bci, 0.0); detailedLog(bci, budget, kbliteral); totalMemory += currentActual; } } if (Memorycapacity == 0) errManager.errorSummary( curMemory, somName, "" + (isROM ? "ROM" : "RAM") + " memory " + curMemory.getComponentInstancePath() + " has no memory capacity specified"); if (totalMemory > Memorycapacity) { errManager.errorSummary( curMemory, somName, "Total Memory " + totalMemory + " KB of bounds tasks exceeds Memory capacity " + Memorycapacity + " KB of " + curMemory.getComponentInstancePath()); } else if (totalMemory == 0.0 && Memorycapacity == 0.0) { errManager.warningSummary( curMemory, somName, "" + (isROM ? "ROM" : "RAM") + " memory " + curMemory.getComponentInstancePath() + " has no capacity. Bound app's have no memory budget."); } else { errManager.infoSummary( curMemory, somName, "Total " + (isROM ? "ROM" : "RAM") + " memory " + totalMemory + " KB of bound tasks within Memory capacity " + Memorycapacity + " KB of " + curMemory.getComponentInstancePath()); } }
public java.util.Iterator<E> iterator() { return copy.iterator(); }
public String generate(Object argument) { final StringBuffer stringBuffer = new StringBuffer(); OwlsCompositeProcess compositeProcess = (OwlsCompositeProcess) argument; Owls owls = compositeProcess.getDescribes().getOwnedBy(); EList<OwlsInput> inputs = compositeProcess.getHasInputs(); EList<OwlsOutput> outputs = compositeProcess.getHasOutputs(); OwlsProcessFacade processFacade = new OwlsProcessFacade(compositeProcess); EList<OwlsProcess> processes = processFacade.getAllProcess(); String ident = new String(); for (Iterator i = processes.iterator(); i.hasNext(); ) { processFacade.setProcessRName((OwlsProcess) i.next()); } stringBuffer.append(TEXT_1); for (Iterator i = processes.iterator(); i.hasNext(); ) { OwlsProcess process = (OwlsProcess) i.next(); stringBuffer.append(TEXT_2); stringBuffer.append(process.getReferenceName()); stringBuffer.append(TEXT_3); stringBuffer.append(processFacade.getProcessURI(process)); stringBuffer.append(TEXT_4); } stringBuffer.append(TEXT_5); stringBuffer.append(owls.getNamespace()); stringBuffer.append(TEXT_6); for (Iterator i = processes.iterator(); i.hasNext(); ) { OwlsProcess process = (OwlsProcess) i.next(); stringBuffer.append(TEXT_7); stringBuffer.append(process.getReferenceName()); stringBuffer.append(TEXT_8); } stringBuffer.append(TEXT_9); stringBuffer.append(owls.getService().getID()); stringBuffer.append(TEXT_10); stringBuffer.append(owls.getProfile().getID()); stringBuffer.append(TEXT_11); stringBuffer.append(owls.getProcess().getID()); stringBuffer.append(TEXT_12); stringBuffer.append(owls.getService().getSupports().getID()); stringBuffer.append(TEXT_13); stringBuffer.append(owls.getProfile().getID()); stringBuffer.append(TEXT_14); stringBuffer.append(owls.getService().getID()); stringBuffer.append(TEXT_15); stringBuffer.append(compositeProcess.getLabel()); stringBuffer.append(TEXT_16); for (Iterator i = inputs.iterator(); i.hasNext(); ) { OwlsInput input = (OwlsInput) i.next(); stringBuffer.append(TEXT_17); stringBuffer.append(input.getID()); stringBuffer.append(TEXT_18); } for (Iterator i = outputs.iterator(); i.hasNext(); ) { OwlsOutput output = (OwlsOutput) i.next(); stringBuffer.append(TEXT_19); stringBuffer.append(output.getID()); stringBuffer.append(TEXT_20); } stringBuffer.append(TEXT_21); stringBuffer.append(owls.getProcess().getID()); stringBuffer.append(TEXT_22); stringBuffer.append(owls.getService().getID()); stringBuffer.append(TEXT_23); for (Iterator i = inputs.iterator(); i.hasNext(); ) { OwlsInput input = (OwlsInput) i.next(); stringBuffer.append(TEXT_24); stringBuffer.append(input.getID()); stringBuffer.append(TEXT_25); String parameterType = input.getParameterType(); if (parameterType.startsWith("http")) { stringBuffer.append(parameterType); } else { stringBuffer.append("&xsd;#" + parameterType); } stringBuffer.append(TEXT_26); } for (Iterator i = outputs.iterator(); i.hasNext(); ) { OwlsOutput output = (OwlsOutput) i.next(); stringBuffer.append(TEXT_27); stringBuffer.append(output.getID()); stringBuffer.append(TEXT_28); String parameterType = output.getParameterType(); if (parameterType.startsWith("http")) { stringBuffer.append(parameterType); } else { stringBuffer.append("&xsd;#" + parameterType); } stringBuffer.append(TEXT_29); } stringBuffer.append(TEXT_30); for (Iterator i = processes.iterator(); i.hasNext(); ) { OwlsProcess process = (OwlsProcess) i.next(); EList<OwlsAssignClient> clientAssings = process.getMessagesBindings(); for (Iterator j = clientAssings.iterator(); j.hasNext(); ) { EObject object = (EObject) j.next(); if (object instanceof OwlsAssignOutputClient) { OwlsAssignOutputClient assignOut = (OwlsAssignOutputClient) object; stringBuffer.append(TEXT_31); stringBuffer.append(assignOut.getProcessReference().getPeformedBy().getID()); stringBuffer.append(TEXT_32); stringBuffer.append(assignOut.getProcessReference().getReferenceName()); stringBuffer.append(TEXT_33); stringBuffer.append(assignOut.getInputReferences().getID()); stringBuffer.append(TEXT_34); stringBuffer.append(assignOut.getOutputsReferences().getID()); stringBuffer.append(TEXT_35); } } } stringBuffer.append(TEXT_36); GenComposition gen = new GenComposition(); List arg = new ArrayList(); List objects = new ArrayList(); objects.add(compositeProcess.getComposedOf()); arg.add(objects); arg.add(ident); stringBuffer.append(gen.generate(arg)); stringBuffer.append(TEXT_37); for (Iterator i = processes.iterator(); i.hasNext(); ) { OwlsProcess process = (OwlsProcess) i.next(); stringBuffer.append(TEXT_38); stringBuffer.append(process.getPeformedBy().getID()); stringBuffer.append(TEXT_39); stringBuffer.append(process.getReferenceName()); stringBuffer.append(TEXT_40); stringBuffer.append(process.getID()); stringBuffer.append(TEXT_41); EList<OwlsAssignClient> clientAssings = process.getMessagesBindings(); for (Iterator j = clientAssings.iterator(); j.hasNext(); ) { EObject object = (EObject) j.next(); if (object instanceof OwlsAssignInputClient) { OwlsAssignInputClient assignIn = (OwlsAssignInputClient) object; stringBuffer.append(TEXT_42); stringBuffer.append(assignIn.getInputReferences().getID()); stringBuffer.append(TEXT_43); stringBuffer.append(assignIn.getProcessReference().getReferenceName()); stringBuffer.append(TEXT_44); stringBuffer.append(assignIn.getOutputsReferences().getID()); stringBuffer.append(TEXT_45); } } EList<OwlsAssign> bindings = process.getBindings(); for (Iterator j = bindings.iterator(); j.hasNext(); ) { EObject object = (EObject) j.next(); OwlsAssign assign = (OwlsAssign) object; stringBuffer.append(TEXT_46); stringBuffer.append(assign.getSource().getPeformedBy().getID()); stringBuffer.append(TEXT_47); stringBuffer.append(assign.getSource().getReferenceName()); stringBuffer.append(TEXT_48); stringBuffer.append(assign.getOutputSource().getID()); stringBuffer.append(TEXT_49); stringBuffer.append(assign.getTarget().getReferenceName()); stringBuffer.append(TEXT_50); stringBuffer.append(assign.getInputTarget().getID()); stringBuffer.append(TEXT_51); } stringBuffer.append(TEXT_52); } stringBuffer.append(TEXT_53); stringBuffer.append(owls.getService().getSupports().getID()); stringBuffer.append(TEXT_54); stringBuffer.append(owls.getService().getID()); stringBuffer.append(TEXT_55); for (Iterator i = processes.iterator(); i.hasNext(); ) { OwlsProcess process = (OwlsProcess) i.next(); EList<OwlsWsdlAtomicProcessGrounding> groundings = process.getDescribes().getSupports().getHasAtomicProcessGrounding(); OwlsWsdlAtomicProcessGrounding atomicGrounding = (OwlsWsdlAtomicProcessGrounding) groundings.get(0); stringBuffer.append(TEXT_56); stringBuffer.append(process.getReferenceName()); stringBuffer.append(TEXT_57); stringBuffer.append(atomicGrounding.getID()); stringBuffer.append(TEXT_58); } stringBuffer.append(TEXT_59); return stringBuffer.toString(); }