file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
StagingServiceImpl.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/staging/impl/StagingServiceImpl.java
package com.hermesworld.ais.galapagos.staging.impl; import com.hermesworld.ais.galapagos.applications.ApplicationsService; import com.hermesworld.ais.galapagos.changes.Change; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.kafka.config.KafkaEnvironmentConfig; import com.hermesworld.ais.galapagos.staging.Staging; import com.hermesworld.ais.galapagos.staging.StagingService; import com.hermesworld.ais.galapagos.subscriptions.service.SubscriptionService; import com.hermesworld.ais.galapagos.topics.service.TopicService; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.util.List; import java.util.concurrent.CompletableFuture; @Component public class StagingServiceImpl implements StagingService { private final KafkaClusters kafkaClusters; private final ApplicationsService applicationsService; private final TopicService topicService; private final SubscriptionService subscriptionService; public StagingServiceImpl(KafkaClusters kafkaClusters, ApplicationsService applicationsService, @Qualifier("nonvalidating") TopicService topicService, SubscriptionService subscriptionService) { this.kafkaClusters = kafkaClusters; this.applicationsService = applicationsService; this.topicService = topicService; this.subscriptionService = subscriptionService; } @Override public CompletableFuture<Staging> prepareStaging(String applicationId, String environmentIdFrom, List<Change> changesFilter) { List<? extends KafkaEnvironmentConfig> environmentMetadata = kafkaClusters.getEnvironmentsMetadata(); String targetEnvironmentId = null; for (int i = 0; i < environmentMetadata.size() - 1; i++) { if (environmentIdFrom.equals(environmentMetadata.get(i).getId())) { targetEnvironmentId = environmentMetadata.get(i + 1).getId(); } } if (targetEnvironmentId == null) { return CompletableFuture.failedFuture(new IllegalArgumentException( "Cannot perform a staging from environment " + environmentIdFrom + ": No next stage found")); } if (applicationsService.getApplicationMetadata(targetEnvironmentId, applicationId).isEmpty()) { return CompletableFuture.failedFuture(new IllegalStateException( "Please create a API Key for the application on the target environment first")); } return StagingImpl.build(applicationId, environmentIdFrom, targetEnvironmentId, changesFilter, topicService, subscriptionService).thenApply(impl -> impl); } }
2,745
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
StagingImpl.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/staging/impl/StagingImpl.java
package com.hermesworld.ais.galapagos.staging.impl; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.hermesworld.ais.galapagos.changes.ApplicableChange; import com.hermesworld.ais.galapagos.changes.ApplyChangeContext; import com.hermesworld.ais.galapagos.changes.Change; import com.hermesworld.ais.galapagos.changes.ChangeType; import com.hermesworld.ais.galapagos.changes.impl.ChangeBase; import com.hermesworld.ais.galapagos.kafka.TopicCreateParams; import com.hermesworld.ais.galapagos.staging.Staging; import com.hermesworld.ais.galapagos.staging.StagingResult; import com.hermesworld.ais.galapagos.subscriptions.SubscriptionMetadata; import com.hermesworld.ais.galapagos.subscriptions.service.SubscriptionService; import com.hermesworld.ais.galapagos.topics.SchemaMetadata; import com.hermesworld.ais.galapagos.topics.TopicMetadata; import com.hermesworld.ais.galapagos.topics.TopicType; import com.hermesworld.ais.galapagos.topics.service.TopicService; import com.hermesworld.ais.galapagos.util.JsonUtil; import lombok.extern.slf4j.Slf4j; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; @Slf4j public final class StagingImpl implements Staging, ApplyChangeContext { private final String applicationId; private final String sourceEnvironmentId; private final String targetEnvironmentId; private final TopicService topicService; private final SubscriptionService subscriptionService; private List<ApplicableChange> changes; private StagingImpl(String applicationId, String sourceEnvironmentId, String targetEnvironmentId, TopicService topicService, SubscriptionService subscriptionService) { this.applicationId = applicationId; this.sourceEnvironmentId = sourceEnvironmentId; this.targetEnvironmentId = targetEnvironmentId; this.topicService = topicService; this.subscriptionService = subscriptionService; } @Override public String getApplicationId() { return applicationId; } @Override public String getSourceEnvironmentId() { return sourceEnvironmentId; } @Override public String getTargetEnvironmentId() { return targetEnvironmentId; } @Override public TopicService getTopicService() { return topicService; } @Override public SubscriptionService getSubscriptionService() { return subscriptionService; } @Override public List<Change> getChanges() { return Collections.unmodifiableList(changes); } @Override public List<StagingResult> perform() { if (changes.isEmpty()) { return Collections.emptyList(); } List<StagingResult> result = new ArrayList<>(); for (ApplicableChange change : changes) { try { change.applyTo(this).get(); result.add(new StagingResult(change, true, null)); } catch (ExecutionException e) { log.info("Staging was not successful due to exception: ", e.getCause()); result.add(new StagingResult(change, false, e.getCause().getMessage())); } catch (InterruptedException e) { return result; } } return result; } public static CompletableFuture<StagingImpl> build(String applicationId, String sourceEnvironmentId, String targetEnvironmentId, List<Change> changesFilter, TopicService topicService, SubscriptionService subscriptionService) { StagingImpl staging = new StagingImpl(applicationId, sourceEnvironmentId, targetEnvironmentId, topicService, subscriptionService); List<ApplicableChange> changes = new ArrayList<>(); List<TopicMetadata> sourceTopics = topicService.listTopics(sourceEnvironmentId).stream() .filter(t -> applicationId.equals(t.getOwnerApplicationId())).collect(Collectors.toList()); List<TopicMetadata> targetTopics = topicService.listTopics(targetEnvironmentId).stream() .filter(t -> applicationId.equals(t.getOwnerApplicationId())).collect(Collectors.toList()); Set<String> createdApiTopics = new HashSet<>(); try { compareSourceTarget(sourceTopics, targetTopics, TopicMetadata::getName, t -> { ApplicableChange change = checkForCreateTopic(t, sourceEnvironmentId, topicService); if (change.getChangeType() == ChangeType.COMPOUND_CHANGE) { createdApiTopics.add(t.getName()); } changes.add(change); }, t -> changes.add(ChangeBase.deleteTopic(t.getName(), t.getType() == TopicType.INTERNAL)), (t1, t2) -> changes.addAll(checkForTopicChanges(t1, t2))); } catch (CompletionException e) { return CompletableFuture.failedFuture(e); } List<SubscriptionMetadata> sourceSubs = subscriptionService.getSubscriptionsOfApplication(sourceEnvironmentId, applicationId, false); List<SubscriptionMetadata> targetSubs = subscriptionService.getSubscriptionsOfApplication(targetEnvironmentId, applicationId, false); compareSourceTarget(sourceSubs, targetSubs, StagingImpl::buildSubscriptionId, s -> changes.add(ChangeBase.subscribeTopic(s)), s -> changes.add(ChangeBase.unsubscribeTopic(s)), null); for (TopicMetadata topic : sourceTopics) { boolean isCreatedApiTopic = createdApiTopics.contains(topic.getName()); List<SchemaMetadata> sourceSchemas = topicService.getTopicSchemaVersions(sourceEnvironmentId, topic.getName()); List<SchemaMetadata> targetSchemas = topicService.getTopicSchemaVersions(targetEnvironmentId, topic.getName()); // created API topics cannot have targetSchemas. Also, we can safely skip the first schema here, // because it has been added in the createTopic change (a compound change). if (isCreatedApiTopic && !sourceSchemas.isEmpty()) { sourceSchemas = sourceSchemas.subList(1, sourceSchemas.size()); } compareSourceTarget(sourceSchemas, targetSchemas, StagingImpl::buildSchemaId, s -> changes.add(ChangeBase.publishTopicSchemaVersion(topic.getName(), s)), null, null); } if (changesFilter != null && !changesFilter.isEmpty()) { addVirtualChanges(changesFilter, changes); // noinspection SuspiciousMethodCalls changes.retainAll(changesFilter); } staging.changes = changes; return CompletableFuture.completedFuture(staging); } private static ApplicableChange checkForCreateTopic(TopicMetadata topic, String sourceEnvironmentId, TopicService topicService) throws CompletionException { SchemaMetadata firstSchema = null; if (topic.getType() != TopicType.INTERNAL) { if (topic.isDeprecated()) { return new CannotStageDeprecatedTopicChange(topic); } List<SchemaMetadata> schemas = topicService.getTopicSchemaVersions(sourceEnvironmentId, topic.getName()); if (schemas.isEmpty()) { return new ApiTopicMissesSchemaChange(topic); } firstSchema = schemas.get(0); } TopicCreateParams createParams = topicService.buildTopicCreateParams(sourceEnvironmentId, topic.getName()) .join(); ChangeBase createChange = ChangeBase.createTopic(topic, createParams); if (topic.getType() != TopicType.INTERNAL) { ChangeBase firstSchemaChange = ChangeBase.publishTopicSchemaVersion(topic.getName(), firstSchema); return ChangeBase.compoundChange(createChange, List.of(firstSchemaChange)); } return createChange; } private static List<ApplicableChange> checkForTopicChanges(TopicMetadata oldTopic, TopicMetadata newTopic) { List<ApplicableChange> result = new ArrayList<>(); if (!Objects.equals(oldTopic.getDescription(), newTopic.getDescription())) { result.add(ChangeBase.updateTopicDescription(newTopic.getName(), newTopic.getDescription(), newTopic.getType() == TopicType.INTERNAL)); } if ((!oldTopic.isDeprecated() && newTopic.isDeprecated()) || (newTopic.isDeprecated() && !Objects.equals(oldTopic.getDeprecationText(), newTopic.getDeprecationText())) || (newTopic.isDeprecated() && !Objects.equals(oldTopic.getEolDate(), newTopic.getEolDate()))) { result.add(ChangeBase.markTopicDeprecated(newTopic.getName(), newTopic.getDeprecationText(), newTopic.getEolDate())); } if (oldTopic.isDeprecated() && !newTopic.isDeprecated()) { result.add(ChangeBase.unmarkTopicDeprecated(newTopic.getName())); } if (oldTopic.isSubscriptionApprovalRequired() != newTopic.isSubscriptionApprovalRequired()) { result.add(ChangeBase.updateTopicSubscriptionApprovalRequiredFlag(newTopic.getName(), newTopic.isSubscriptionApprovalRequired())); } List<String> oldProducers = Optional.ofNullable(oldTopic.getProducers()).orElse(List.of()); List<String> newProducers = Optional.ofNullable(newTopic.getProducers()).orElse(List.of()); if (!oldProducers.equals(newProducers)) { List<String> producerIdsToBeAdded = newProducers.stream() .filter(producer -> !oldProducers.contains(producer)).collect(Collectors.toList()); producerIdsToBeAdded .forEach(producerId -> result.add(ChangeBase.addTopicProducer(newTopic.getName(), producerId))); List<String> ids = new ArrayList<>(oldProducers); ids.removeAll(newProducers); List<String> toBeDeletedIds = new ArrayList<>(ids); toBeDeletedIds .forEach(producerId -> result.add(ChangeBase.removeTopicProducer(newTopic.getName(), producerId))); } return result; } private static String buildSubscriptionId(SubscriptionMetadata subscription) { return subscription.getClientApplicationId() + "-" + subscription.getTopicName(); } private static String buildSchemaId(SchemaMetadata schema) { return schema.getTopicName() + "-" + schema.getSchemaVersion(); } private static <T> void compareSourceTarget(Collection<T> source, Collection<T> target, Function<T, String> idProvider, Consumer<T> createdHandler, Consumer<T> deletedHandler, BiConsumer<T, T> checkForChangesHandler) { for (T tSrc : source) { String id = idProvider.apply(tSrc); T tTgt = target.stream().filter(t -> id.equals(idProvider.apply(t))).findFirst().orElse(null); if (tTgt == null) { createdHandler.accept(tSrc); } else if (checkForChangesHandler != null) { checkForChangesHandler.accept(tTgt, tSrc); } } if (deletedHandler != null) { for (T tTgt : target) { String id = idProvider.apply(tTgt); T tSrc = source.stream().filter(t -> id.equals(idProvider.apply(t))).findFirst().orElse(null); if (tSrc == null) { deletedHandler.accept(tTgt); } } } } private static void addVirtualChanges(List<Change> changesFilter, List<ApplicableChange> calculatedChanges) { // special treatment: If changes filter contains a "CREATE_TOPIC" for which we have a matching // VirtualChange change, THAT should be included, so user gets the error message! for (Change change : new ArrayList<>(changesFilter)) { if (change.getChangeType() == ChangeType.TOPIC_CREATED) { ObjectMapper mapper = JsonUtil.newObjectMapper(); try { String json1 = mapper.writeValueAsString(change); for (Change change2 : calculatedChanges) { if (change2 instanceof VirtualChange) { String json2 = mapper.writeValueAsString(change2); if (json1.equals(json2)) { changesFilter.add(change2); } } } } catch (JsonProcessingException e) { // ignore here; just continue with next change } } } } /** * Marker interface for changes which are "virtual", so are not automatically deserialized from JSON. See below * classes for examples. */ private interface VirtualChange extends ApplicableChange { } /** * Dummy change class which always fails, because there is no published schema for the API topic. */ @JsonSerialize static class ApiTopicMissesSchemaChange implements VirtualChange { private final TopicMetadata topicMetadata; public ApiTopicMissesSchemaChange(TopicMetadata topicMetadata) { this.topicMetadata = topicMetadata; } public TopicMetadata getTopicMetadata() { return topicMetadata; } @Override public ChangeType getChangeType() { return ChangeType.TOPIC_CREATED; } @Override public CompletableFuture<?> applyTo(ApplyChangeContext context) { return CompletableFuture.failedFuture( new IllegalStateException("API Topic cannot be staged without a published JSON schema")); } } /** * Dummy change class which always fails, because deprecated topics cannot be staged. */ @JsonSerialize static class CannotStageDeprecatedTopicChange implements VirtualChange { private final TopicMetadata topicMetadata; public CannotStageDeprecatedTopicChange(TopicMetadata topicMetadata) { this.topicMetadata = topicMetadata; } public TopicMetadata getTopicMetadata() { return topicMetadata; } @Override public ChangeType getChangeType() { return ChangeType.TOPIC_CREATED; } @Override public CompletableFuture<?> applyTo(ApplyChangeContext context) { return CompletableFuture.failedFuture(new IllegalStateException("Deprecated topics cannot be staged.")); } } }
15,129
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
TrustStoreController.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/controller/TrustStoreController.java
package com.hermesworld.ais.galapagos.certificates.controller; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.kafka.auth.KafkaAuthenticationModule; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.common.config.SslConfigs; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.ObjectUtils; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import java.util.function.Supplier; @RestController @Slf4j public class TrustStoreController { private final KafkaClusters kafkaClusters; private final Supplier<ResponseStatusException> notFound = () -> new ResponseStatusException(HttpStatus.NOT_FOUND); public TrustStoreController(KafkaClusters kafkaClusters) { this.kafkaClusters = kafkaClusters; } // intentionally not protected - no /api path @GetMapping(value = "/files/truststore/{environmentId}", produces = "application/x-pkcs12") public ResponseEntity<byte[]> getTrustStore(@PathVariable String environmentId) { String authMode = kafkaClusters.getEnvironmentMetadata(environmentId).map(meta -> meta.getAuthenticationMode()) .orElseThrow(notFound); if (!"certificates".equals(authMode)) { throw notFound.get(); } // trick to extract trust store - use Kafka properties! KafkaAuthenticationModule module = kafkaClusters.getAuthenticationModule(environmentId).orElseThrow(notFound); Properties props = new Properties(); module.addRequiredKafkaProperties(props); String trustStoreLocation = props.getProperty(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG); if (ObjectUtils.isEmpty(trustStoreLocation)) { throw notFound.get(); } try (FileInputStream fis = new FileInputStream(trustStoreLocation)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamUtils.copy(fis, baos); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=kafka-truststore-" + environmentId + ".jks"); return new ResponseEntity<>(baos.toByteArray(), responseHeaders, HttpStatus.OK); } catch (IOException e) { log.error("Could not read truststore " + trustStoreLocation, e); throw notFound.get(); } } }
2,892
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
CertificateExpiryReminder.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/CertificateExpiryReminder.java
package com.hermesworld.ais.galapagos.certificates.reminders; import lombok.Getter; /** * Represents a reminder about the expiration of a certificate which should be sent out. * * @author AlbrechtFlo */ @Getter public final class CertificateExpiryReminder { private final String applicationId; private final String environmentId; private final ReminderType reminderType; /** * Constructs a new reminder instance. * * @param applicationId The ID of the application this reminder is for. * @param environmentId The ID of the environment for which this certificate is valid. * @param reminderType The type of the reminder, e.g. three-months-reminder. */ public CertificateExpiryReminder(String applicationId, String environmentId, ReminderType reminderType) { this.applicationId = applicationId; this.environmentId = environmentId; this.reminderType = reminderType; } }
957
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
ReminderType.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/ReminderType.java
package com.hermesworld.ais.galapagos.certificates.reminders; import java.time.Instant; import java.time.temporal.ChronoUnit; /** * Types of certificate expiry reminders which are sent. Each type can be queried for the number of days before * certificate expiry a reminder of this type should be sent. */ public enum ReminderType { ONE_WEEK(7), ONE_MONTH(30), THREE_MONTHS(90); private final int daysToAdd; /** * Constructs a new enum value which adds the given amount of days in its {@link #calculateInstant(Instant)} method. * * @param daysToAdd Days to add when {@link #calculateInstant(Instant)} is called. */ ReminderType(int daysToAdd) { this.daysToAdd = daysToAdd; } /** * Adds an amount of days to the given instant and returns the resulting instant. * * @param now Instant to add days to. * * @return Instant with days added to the given instant. */ public Instant calculateInstant(Instant now) { return now.plus(this.daysToAdd, ChronoUnit.DAYS); } }
1,068
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
CertificateExpiryReminderService.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/CertificateExpiryReminderService.java
package com.hermesworld.ais.galapagos.certificates.reminders; import java.util.List; /** * A service which is able to calculate the due reminders for application topic owners about the expiry of one of their * certificates. The service ensures that one reminder is reported to be sent (each), when * <ul> * <li>the certificate expires in less than three months</li>, * <li>the certificate expires in less than one month</li>, * <li>the certificate expires in less than one week.</li> * </ul> * As soon as a reminder is reported to have been sent, the reminder will not be reported again for the same expiry * period (even after restarts of Galapagos). * * @author AlbrechtFlo * @author SoltaniFaz */ public interface CertificateExpiryReminderService { /** * Calculates for which application certificates a reminder is currently due (and has not been sent out yet). * * @return A list of reminders which should be sent out by the caller. Reminders may only occur in this list until * they have been marked as sent out by a call to {@link #markReminderSentOut(CertificateExpiryReminder)}. */ List<CertificateExpiryReminder> calculateDueCertificateReminders(); /** * Informs the repository that a reminder (which has been returned by {@link #calculateDueCertificateReminders()}) * has been sent out successfully and should no longer be returned as being due. * * @param reminder Reminder to mark as sent out. */ void markReminderSentOut(CertificateExpiryReminder reminder); }
1,565
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
CertificateExpiryReminderServiceImpl.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderServiceImpl.java
package com.hermesworld.ais.galapagos.certificates.reminders.impl; import com.hermesworld.ais.galapagos.applications.ApplicationMetadata; import com.hermesworld.ais.galapagos.applications.ApplicationsService; import com.hermesworld.ais.galapagos.certificates.reminders.CertificateExpiryReminder; import com.hermesworld.ais.galapagos.certificates.reminders.CertificateExpiryReminderService; import com.hermesworld.ais.galapagos.certificates.reminders.ReminderType; import com.hermesworld.ais.galapagos.kafka.KafkaCluster; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.kafka.auth.KafkaAuthenticationModule; import com.hermesworld.ais.galapagos.kafka.config.KafkaEnvironmentConfig; import com.hermesworld.ais.galapagos.kafka.util.InitPerCluster; import com.hermesworld.ais.galapagos.kafka.util.TopicBasedRepository; import lombok.extern.slf4j.Slf4j; import org.json.JSONException; import org.json.JSONObject; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.time.Instant; import java.util.*; @Service @Slf4j public class CertificateExpiryReminderServiceImpl implements CertificateExpiryReminderService, InitPerCluster { private final KafkaClusters kafkaClusters; private final ApplicationsService applicationsService; private static final String REPOSITORY_NAME = "reminders"; public CertificateExpiryReminderServiceImpl(KafkaClusters kafkaClusters, ApplicationsService applicationsService) { this.kafkaClusters = kafkaClusters; this.applicationsService = applicationsService; } @Override public void init(KafkaCluster cluster) { getRepository(cluster).getObjects(); } @Override public List<CertificateExpiryReminder> calculateDueCertificateReminders() { List<CertificateExpiryReminder> result = new ArrayList<>(); Instant now = Instant.now(); for (KafkaCluster cluster : kafkaClusters.getEnvironments()) { KafkaEnvironmentConfig envMeta = kafkaClusters.getEnvironmentMetadata(cluster.getId()).orElse(null); KafkaAuthenticationModule authModule = kafkaClusters.getAuthenticationModule(cluster.getId()).orElse(null); if (envMeta == null || authModule == null || !"certificates".equals(envMeta.getAuthenticationMode())) { continue; } List<ApplicationMetadata> allMetadata = applicationsService.getAllApplicationMetadata(cluster.getId()); Collection<ReminderMetadata> sentReminders = getRepository(cluster).getObjects(); for (ApplicationMetadata app : allMetadata) { if (!StringUtils.hasLength(app.getAuthenticationJson())) { continue; } JSONObject authData; try { authData = new JSONObject(app.getAuthenticationJson()); } catch (JSONException e) { log.error("Invalid JSON in authentication data of application " + app.getApplicationId(), e); continue; } Optional<Instant> certExpires = authModule.extractExpiryDate(authData); if (certExpires.isEmpty()) { log.warn("No expiresAt found in authentication data of application " + app.getApplicationId()); continue; } for (ReminderType reminderType : ReminderType.values()) { if (certExpires.get().isBefore(reminderType.calculateInstant(now))) { CertificateExpiryReminder reminder = new CertificateExpiryReminder(app.getApplicationId(), cluster.getId(), reminderType); if (!containsReminder(sentReminders, reminder)) { result.add(reminder); } // break in any case, as, if a reminder e.g. for one_week has been sent already, we won't return // a reminder for one_month or three_months (although it has never been sent). break; } } } } return result; } @Override public void markReminderSentOut(CertificateExpiryReminder reminder) { KafkaCluster clusterOfEnv = kafkaClusters.getEnvironment(reminder.getEnvironmentId()).orElseThrow(); ReminderMetadata metadata = new ReminderMetadata(); metadata.setApplicationId(reminder.getApplicationId()); metadata.setReminderType(reminder.getReminderType()); metadata.setReminderId(UUID.randomUUID().toString()); getRepository(clusterOfEnv).save(metadata); } private boolean containsReminder(Collection<ReminderMetadata> metadatas, CertificateExpiryReminder reminder) { return metadatas.stream().anyMatch(meta -> meta.getApplicationId().equals(reminder.getApplicationId()) && meta.getReminderType().equals(reminder.getReminderType())); } private TopicBasedRepository<ReminderMetadata> getRepository(KafkaCluster cluster) { return cluster.getRepository(REPOSITORY_NAME, ReminderMetadata.class); } }
5,284
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
CertificateExpiryReminderRunner.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/CertificateExpiryReminderRunner.java
package com.hermesworld.ais.galapagos.certificates.reminders.impl; import com.hermesworld.ais.galapagos.applications.ApplicationMetadata; import com.hermesworld.ais.galapagos.applications.ApplicationsService; import com.hermesworld.ais.galapagos.certificates.reminders.CertificateExpiryReminder; import com.hermesworld.ais.galapagos.certificates.reminders.CertificateExpiryReminderService; import com.hermesworld.ais.galapagos.kafka.KafkaClusters; import com.hermesworld.ais.galapagos.kafka.auth.KafkaAuthenticationModule; import com.hermesworld.ais.galapagos.notifications.NotificationParams; import com.hermesworld.ais.galapagos.notifications.NotificationService; import lombok.extern.slf4j.Slf4j; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.time.DateTimeException; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; /** * Scheduling component which checks every six hours for new certificate expiry notifications to be sent (first check is * performed five minutes after application startup). */ @Component @Slf4j public class CertificateExpiryReminderRunner { private final CertificateExpiryReminderService reminderService; private final NotificationService notificationService; private final ApplicationsService applicationsService; private final KafkaClusters kafkaClusters; private final String timezone; public CertificateExpiryReminderRunner(CertificateExpiryReminderService reminderService, NotificationService notificationService, ApplicationsService applicationsService, KafkaClusters kafkaClusters, @Value("${galapagos.timezone:GMT}") String timezone) { this.reminderService = reminderService; this.notificationService = notificationService; this.applicationsService = applicationsService; this.kafkaClusters = kafkaClusters; this.timezone = timezone; } /** * Check for new certificate expiry notifications to be sent. Is called by Spring Scheduler. */ @Scheduled(initialDelayString = "PT5M", fixedDelayString = "PT6H") public void checkCertificatesForExpiration() { log.info("Checking for soon expiring certificates..."); List<CertificateExpiryReminder> reminders = reminderService.calculateDueCertificateReminders(); log.info("Found {} certificate expiry reminder(s) to be sent.", reminders.size()); for (CertificateExpiryReminder reminder : reminders) { try { sendReminderEmail(reminder).thenAccept(v -> reminderService.markReminderSentOut(reminder)).get(); } catch (ExecutionException e) { log.error("Could not send out certificate expiration reminder e-mail for application " + reminder.getApplicationId(), e.getCause()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } } private CompletableFuture<Void> sendReminderEmail(CertificateExpiryReminder reminder) { NotificationParams params = new NotificationParams( "certificate-reminder-" + reminder.getReminderType().name().toLowerCase(Locale.US)); params.addVariable("app_name", getApplicationName(reminder.getApplicationId())); params.addVariable("expiry_date", getDateOfExpiry(reminder.getApplicationId(), reminder.getEnvironmentId())); params.addVariable("environment_name", kafkaClusters.getEnvironmentMetadata(reminder.getEnvironmentId()) .map(env -> env.getName()).orElse(reminder.getEnvironmentId())); return notificationService.notifyApplicationTopicOwners(reminder.getApplicationId(), params); } private String getApplicationName(String applicationId) { return applicationsService.getKnownApplications(false).stream().filter(app -> applicationId.equals(app.getId())) .map(app -> app.getName()).findAny().orElse("(Unknown application)"); } private ZonedDateTime getDateOfExpiry(String applicationId, String environmentId) { return applicationsService.getApplicationMetadata(environmentId, applicationId) .map(meta -> getDateOfExpiry(meta, environmentId)).orElse(null); } private ZonedDateTime getDateOfExpiry(ApplicationMetadata metadata, String environmentId) { KafkaAuthenticationModule authModule = kafkaClusters.getAuthenticationModule(environmentId).orElseThrow(); if (!StringUtils.hasLength(metadata.getAuthenticationJson())) { return null; } ZoneId tz; try { tz = ZoneId.of(timezone); } catch (DateTimeException e) { tz = ZoneId.of("Z"); } try { Optional<Instant> expAt = authModule.extractExpiryDate(new JSONObject(metadata.getAuthenticationJson())); return expAt.isEmpty() ? null : ZonedDateTime.ofInstant(expAt.get(), tz); } catch (JSONException e) { log.error("Invalid Authentication JSON for application ID " + metadata.getApplicationId()); return null; } } }
5,596
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
ReminderMetadata.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/reminders/impl/ReminderMetadata.java
package com.hermesworld.ais.galapagos.certificates.reminders.impl; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.hermesworld.ais.galapagos.certificates.reminders.ReminderType; import com.hermesworld.ais.galapagos.util.HasKey; import lombok.Getter; import lombok.Setter; /** * Metadata for a certificate expiry reminder which has been sent for a given application ID and reminder type. * Instances of this type are stored in the Galapagos Metadata topic <code>reminders</code>. */ @JsonSerialize @Getter @Setter public class ReminderMetadata implements HasKey { private String reminderId; private String applicationId; private ReminderType reminderType; @Override public String key() { return reminderId; } }
779
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
CaManagerImpl.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/impl/CaManagerImpl.java
package com.hermesworld.ais.galapagos.certificates.impl; import com.hermesworld.ais.galapagos.certificates.auth.CertificatesAuthenticationConfig; import com.hermesworld.ais.galapagos.util.CertificateUtil; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.DERBMPString; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509ExtensionUtils; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils; import org.bouncycastle.crypto.util.PrivateKeyFactory; import org.bouncycastle.openssl.MiscPEMGenerator; import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.pkcs.PKCS12PfxPduBuilder; import org.bouncycastle.pkcs.PKCS12SafeBag; import org.bouncycastle.pkcs.PKCSException; import org.bouncycastle.pkcs.bc.BcPKCS12MacCalculatorBuilder; import org.bouncycastle.pkcs.jcajce.JcaPKCS12SafeBagBuilder; import org.bouncycastle.util.io.pem.PemWriter; import org.springframework.util.StringUtils; import java.io.*; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.time.Duration; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Date; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; /** * Manages the CA for a single Kafka Cluster. * * @author AlbrechtFlo */ @Slf4j public final class CaManagerImpl { private final CaData caData; private final String environmentId; private File p12File; private String p12Password; private static final long DEFAULT_CERTIFICATE_VALIDITY = Duration.ofDays(365).toMillis(); private static final long TOOLING_VALIDITY = Duration.ofDays(3650).toMillis(); private static final int PKCS12_PASSWORD_LENGTH = 8; private static final ASN1ObjectIdentifier TRUSTED_KEY_USAGE = new ASN1ObjectIdentifier( "2.16.840.1.113894.746875.1.1"); private static final ASN1ObjectIdentifier ANY_EXTENDED_KEY_USAGE = new ASN1ObjectIdentifier("2.5.29.37.0"); private static final Random RANDOM = new Random(); public CaManagerImpl(String environmentId, CertificatesAuthenticationConfig config) throws IOException, GeneralSecurityException, OperatorCreationException { this.environmentId = environmentId; this.caData = buildCaData(environmentId, config); generateGalapagosPkcs12ClientCertificate(environmentId, config.getClientDn(), new File(config.getCertificatesWorkdir())); } public CompletableFuture<CertificateSignResult> createApplicationCertificateFromCsr(String applicationId, String csrData, String applicationName) { try (PEMParser parser = new PEMParser(new StringReader(csrData))) { Object o = parser.readObject(); if (!(o instanceof PKCS10CertificationRequest)) { return CompletableFuture .failedFuture(new CertificateException("Invalid CSR data: no request found in data")); } return createCertificate((PKCS10CertificationRequest) o, CertificateUtil.toAppCn(applicationName), caData.getApplicationCertificateValidity()); } catch (IOException e) { return CompletableFuture.failedFuture(new CertificateException("Invalid CSR data", e)); } } public CompletableFuture<CertificateSignResult> createApplicationCertificateAndPrivateKey(String applicationId, String applicationName) { return createCertificateAndPrivateKey(applicationName, caData.getApplicationCertificateValidity()); } public CompletableFuture<CertificateSignResult> createToolingCertificateAndPrivateKey() { return createCertificateAndPrivateKey("galapagos_tooling", TOOLING_VALIDITY); } public CompletableFuture<CertificateSignResult> extendApplicationCertificate(String dn, String csrData) { X500Name parsedDn = parseAndSortDn(dn); try (PEMParser parser = new PEMParser(new StringReader(csrData))) { Object o = parser.readObject(); if (!(o instanceof PKCS10CertificationRequest)) { return CompletableFuture .failedFuture(new CertificateException("Invalid CSR data: no request found in data")); } PKCS10CertificationRequest csr = (PKCS10CertificationRequest) o; if (!parsedDn.equals(csr.getSubject())) { return CompletableFuture.failedFuture( new CertificateParsingException("The CSR is not valid for extending this certificate")); } return createCertificate(csr, parsedDn, caData.getApplicationCertificateValidity()); } catch (IOException e) { return CompletableFuture.failedFuture(new CertificateException("Invalid CSR data", e)); } } public boolean supportsDeveloperCertificates() { return caData.getDeveloperCertificateValidity() > 0; } public CompletableFuture<CertificateSignResult> createDeveloperCertificateAndPrivateKey(String userName) { if (!supportsDeveloperCertificates()) { return CompletableFuture.failedFuture( new IllegalStateException("Developer certificates are not enabled for this environment.")); } return createCertificateAndPrivateKey(userName, caData.getDeveloperCertificateValidity()); } public byte[] buildTrustStore() throws IOException, PKCSException { PKCS12PfxPduBuilder keyStoreBuilder = new PKCS12PfxPduBuilder(); keyStoreBuilder.addData(new JcaPKCS12SafeBagBuilder(getCaCertificate()) .addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("kafka_" + environmentId + "_ca")) .addBagAttribute(TRUSTED_KEY_USAGE, ANY_EXTENDED_KEY_USAGE).build()); return keyStoreBuilder.build(new BcPKCS12MacCalculatorBuilder(), "changeit".toCharArray()) .getEncoded(ASN1Encoding.DL); } public File getClientPkcs12File() { return p12File; } public String getClientPkcs12Password() { return p12Password; } private CompletableFuture<CertificateSignResult> createCertificateAndPrivateKey(String userOrAppName, long validityMs) { String cn = CertificateUtil.toAppCn(userOrAppName); try { KeyPair pair = CertificateUtil.generateKeyPair(); X500Name name = CertificateUtil.uniqueX500Name(cn); PKCS10CertificationRequest csr = CertificateUtil.buildCsr(name, pair); return createCertificate(csr, cn, validityMs).thenCompose(result -> { try { return CompletableFuture.completedFuture(new CertificateSignResult(result.getCertificate(), result.getCertificatePemData(), result.getDn(), CertificateUtil.buildPrivateKeyStore( result.getCertificate(), pair.getPrivate(), "changeit".toCharArray()))); } catch (OperatorCreationException | PKCSException e) { return CompletableFuture.failedFuture( new CertificateException("Could not generate internal CSR for certificate", e)); } catch (GeneralSecurityException e) { return CompletableFuture.failedFuture( new RuntimeException("Java Security is configured wrong, or Bouncycastle not found")); } catch (IOException e) { // should not occur in-memory return CompletableFuture .failedFuture(new RuntimeException("Exception when writing into memory", e)); } }); } catch (GeneralSecurityException e) { return CompletableFuture .failedFuture(new RuntimeException("Java Security is configured wrong, or Bouncycastle not found")); } catch (OperatorCreationException e) { return CompletableFuture .failedFuture(new CertificateException("Could not generate internal CSR for certificate", e)); } } private void generateGalapagosPkcs12ClientCertificate(String envId, String dn, File certificateWorkdir) throws GeneralSecurityException, OperatorCreationException { KeyPair pair = CertificateUtil.generateKeyPair(); X500Name name = new X500Name(dn); PKCS10CertificationRequest csr = CertificateUtil.buildCsr(name, pair); X509CertificateHolder holder = signCertificateRequest(csr, name, ChronoUnit.YEARS.getDuration().toMillis() * 10); X509Certificate publicCert = new JcaX509CertificateConverter().getCertificate(holder); try { String password = generatePkcs12Password(); byte[] data = CertificateUtil.buildPrivateKeyStore(publicCert, pair.getPrivate(), password.toCharArray()); if (!certificateWorkdir.isDirectory() && !certificateWorkdir.mkdirs()) { throw new IOException( "Could not create certificate working directory " + certificateWorkdir.getAbsolutePath()); } File fCertificate = new File(certificateWorkdir, "galapagos_" + envId + "_client.p12"); try (FileOutputStream fos = new FileOutputStream(fCertificate)) { fos.write(data); } this.p12File = fCertificate; this.p12Password = password; } catch (IOException | PKCSException e) { throw new GeneralSecurityException(e); } } private CompletableFuture<CertificateSignResult> createCertificate(PKCS10CertificationRequest csr, String commonName, long validityMs) { String cn = CertificateUtil.extractCn(csr.getSubject()); // MUST match application name if (cn == null) { return CompletableFuture.failedFuture( new CertificateParsingException("No CN attribute present in Certificate Request. Please include CN=" + commonName + " as subject in the request.")); } if (!cn.equals(commonName)) { return CompletableFuture .failedFuture(new CertificateParsingException("Wrong CN in Certificate Request. Please include CN=" + commonName + " as subject in the request.")); } return createCertificate(csr, CertificateUtil.uniqueX500Name(commonName), validityMs); } private CompletableFuture<CertificateSignResult> createCertificate(PKCS10CertificationRequest csr, X500Name dn, long validityMs) { StringBuilder pemData = new StringBuilder(); X509Certificate certificate; try { certificate = createSignedPemCertificate(csr, dn, pemData, validityMs); } catch (CertificateException e) { return CompletableFuture.failedFuture(e); } String newDn = certificate.getSubjectX500Principal().toString().replace(", OU=", ",OU="); return CompletableFuture .completedFuture(new CertificateSignResult(certificate, pemData.toString(), newDn, null)); } private X509Certificate createSignedPemCertificate(PKCS10CertificationRequest csr, X500Name dn, StringBuilder pemDataHolder, long validityMs) throws CertificateException { try { X509CertificateHolder holder = signCertificateRequest(csr, dn, validityMs); StringWriter sw = new StringWriter(); try (PemWriter writer = new PemWriter(sw)) { writer.writeObject(new MiscPEMGenerator(holder)); } pemDataHolder.append(sw); return new JcaX509CertificateConverter().getCertificate(holder); } catch (IOException e) { throw new CertificateException("Exception during reading certificate data", e); } catch (OperatorCreationException e) { throw new CertificateException("Could not sign certificate", e); } catch (CertificateParsingException e) { throw e; } catch (GeneralSecurityException e) { // intentional RuntimeException as this should fall through throw new RuntimeException("Missing algorithm or other configuration problem for certificate signing", e); } } private X509CertificateHolder signCertificateRequest(PKCS10CertificationRequest csr, X500Name subject, long validityMs) throws GeneralSecurityException, OperatorCreationException { X500Name caName = new JcaX509CertificateHolder(caData.getCaCertificate()).getSubject(); X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(caName, getSerial(subject), new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)), new Date(System.currentTimeMillis() + validityMs), subject, csr.getSubjectPublicKeyInfo()); try { certGenerator.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); X509ExtensionUtils utils = new JcaX509ExtensionUtils(); certGenerator.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(csr.getSubjectPublicKeyInfo())); X509CertificateHolder caHolder = new X509CertificateHolder(caData.getCaCertificate().getEncoded()); certGenerator.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(caHolder)); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(PrivateKeyFactory.createKey(caData.getCaPrivateKey().getEncoded())); return certGenerator.build(signer); } catch (IOException e) { throw new GeneralSecurityException(e); } } private BigInteger getSerial(X500Name name) { BigInteger millis = BigInteger.valueOf(System.currentTimeMillis()); millis = millis.multiply(BigInteger.valueOf(Integer.MAX_VALUE)); return millis.add(BigInteger.valueOf(name.toString().hashCode())); } private X509Certificate getCaCertificate() { return caData.getCaCertificate(); } private static CaData buildCaData(String environmentId, CertificatesAuthenticationConfig config) throws IOException, GeneralSecurityException { CaData data = new CaData(); if (config.getCaCertificateFile() == null) { throw new RuntimeException( "Missing configuration property caCertificateFile for environment " + environmentId); } if (config.getCaKeyFile() == null) { throw new RuntimeException("Missing configuration property caKeyFile for environment " + environmentId); } try (InputStream inPublic = config.getCaCertificateFile().getInputStream(); PEMParser keyParser = new PEMParser( new InputStreamReader(config.getCaKeyFile().getInputStream(), StandardCharsets.ISO_8859_1))) { data.setCaCertificate( (X509Certificate) CertificateFactory.getInstance("X.509", "BC").generateCertificate(inPublic)); Object object = keyParser.readObject(); JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); PEMKeyPair ukp = (PEMKeyPair) object; KeyPair kp = converter.getKeyPair(ukp); if (!Arrays.equals(kp.getPublic().getEncoded(), data.getCaCertificate().getPublicKey().getEncoded())) { throw new RuntimeException("The public/private key pair does not match for certificate " + data.getCaCertificate().getSubjectX500Principal().getName()); } data.setCaPrivateKey(kp.getPrivate()); } try { data.setApplicationCertificateValidity( !StringUtils.hasLength(config.getApplicationCertificateValidity()) ? DEFAULT_CERTIFICATE_VALIDITY : Duration.parse(config.getApplicationCertificateValidity()).toMillis()); } catch (DateTimeParseException e) { log.warn("Invalid duration pattern found in application configuration: " + config.getApplicationCertificateValidity()); data.setApplicationCertificateValidity(DEFAULT_CERTIFICATE_VALIDITY); } try { data.setDeveloperCertificateValidity(!StringUtils.hasLength(config.getDeveloperCertificateValidity()) ? 0 : Duration.parse(config.getDeveloperCertificateValidity()).toMillis()); } catch (DateTimeParseException e) { log.warn("Invalid duration pattern found in application configuration: " + config.getApplicationCertificateValidity()); data.setApplicationCertificateValidity(DEFAULT_CERTIFICATE_VALIDITY); } return data; } private static String generatePkcs12Password() { String allowedChars = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; StringBuilder sbPass = new StringBuilder(); for (int i = 0; i < PKCS12_PASSWORD_LENGTH; i++) { sbPass.append(allowedChars.charAt(RANDOM.nextInt(allowedChars.length()))); } return sbPass.toString(); } private static X500Name parseAndSortDn(String rawDn) { X500Name name = new X500Name(rawDn); if (name.getRDNs(X509ObjectIdentifiers.organizationalUnitName).length == 0) { return name; } X500NameBuilder builder = new X500NameBuilder(); builder.addRDN(name.getRDNs(X509ObjectIdentifiers.organizationalUnitName)[0].getFirst()); builder.addRDN(name.getRDNs(X509ObjectIdentifiers.commonName)[0].getFirst()); return builder.build(); } }
19,788
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
CaData.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/impl/CaData.java
package com.hermesworld.ais.galapagos.certificates.impl; import java.security.PrivateKey; import java.security.cert.X509Certificate; import lombok.Getter; import lombok.Setter; @Getter @Setter final class CaData { private X509Certificate caCertificate; private PrivateKey caPrivateKey; private long applicationCertificateValidity; private long developerCertificateValidity; }
400
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
CertificateSignResult.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/impl/CertificateSignResult.java
package com.hermesworld.ais.galapagos.certificates.impl; import lombok.Getter; import java.security.cert.X509Certificate; import java.util.Optional; @Getter public final class CertificateSignResult { private final X509Certificate certificate; private final String certificatePemData; private final Optional<byte[]> p12Data; private final String dn; public CertificateSignResult(X509Certificate certificate, String certificatePemData, String dn, byte[] p12Data) { this.certificate = certificate; this.certificatePemData = certificatePemData; this.dn = dn; this.p12Data = Optional.ofNullable(p12Data); } }
669
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
CertificatesAuthenticationModule.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/auth/CertificatesAuthenticationModule.java
package com.hermesworld.ais.galapagos.certificates.auth; import com.hermesworld.ais.galapagos.certificates.impl.CaManagerImpl; import com.hermesworld.ais.galapagos.certificates.impl.CertificateSignResult; import com.hermesworld.ais.galapagos.kafka.auth.CreateAuthenticationResult; import com.hermesworld.ais.galapagos.kafka.auth.KafkaAuthenticationModule; import com.hermesworld.ais.galapagos.util.FutureUtil; import org.apache.kafka.clients.CommonClientConfigs; import org.apache.kafka.common.config.SslConfigs; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.pkcs.PKCSException; import org.json.JSONException; import org.json.JSONObject; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.concurrent.CompletableFuture; public class CertificatesAuthenticationModule implements KafkaAuthenticationModule { private final String environmentId; private final CertificatesAuthenticationConfig config; private CaManagerImpl caManager; private String truststoreFile; private String truststorePassword; private final static String EXPIRES_AT = "expiresAt"; private final static String DN = "dn"; public CertificatesAuthenticationModule(String environmentId, CertificatesAuthenticationConfig config) { this.environmentId = environmentId; this.config = config; } @Override public CompletableFuture<Void> init() { try { Files.createDirectories(Path.of(config.getCertificatesWorkdir())); this.caManager = new CaManagerImpl(environmentId, config); if (!StringUtils.hasLength(config.getTruststoreFile())) { createDynamicTruststore(); } else { this.truststoreFile = config.getTruststoreFile(); this.truststorePassword = config.getTruststorePassword(); } return CompletableFuture.completedFuture(null); } catch (IOException | GeneralSecurityException | OperatorCreationException | PKCSException e) { return CompletableFuture.failedFuture(e); } } @Override public CompletableFuture<CreateAuthenticationResult> createApplicationAuthentication(String applicationId, String applicationNormalizedName, JSONObject createParameters) { boolean extendCertificate = createParameters.optBoolean("extendCertificate", false); // wrong method called for extending certificate! if (extendCertificate) { return CompletableFuture.failedFuture(new IllegalArgumentException( "Cannot extend certificate - application does not yet have certificate on this environment")); } return createOrUpdateApplicationAuthentication(applicationId, applicationNormalizedName, createParameters, null); } @Override public CompletableFuture<CreateAuthenticationResult> updateApplicationAuthentication(String applicationId, String applicationNormalizedName, JSONObject createParameters, JSONObject existingAuthData) { boolean extendCertificate = createParameters.optBoolean("extendCertificate", false); String dn = null; if (extendCertificate) { dn = existingAuthData.optString(DN); if (ObjectUtils.isEmpty(dn)) { return CompletableFuture.failedFuture(new IllegalArgumentException( "Cannot extend certificate - no certificate information available for application")); } } return createOrUpdateApplicationAuthentication(applicationId, applicationNormalizedName, createParameters, dn); } private CompletableFuture<CreateAuthenticationResult> createOrUpdateApplicationAuthentication(String applicationId, String applicationNormalizedName, JSONObject createParameters, String dn) { boolean generateKey = createParameters.optBoolean("generateKey", false); ByteArrayOutputStream outSecret = new ByteArrayOutputStream(); if (!generateKey) { String csr = createParameters.optString("csrData"); if (ObjectUtils.isEmpty(csr)) { return CompletableFuture.failedFuture(new IllegalArgumentException( "No CSR (csrData) present! Set generateKey to true if you want the server to generate a private key for you (not recommended).")); } return createApplicationCertificateFromCsr(applicationId, applicationNormalizedName, csr, dn, outSecret) .thenApply(result -> new CreateAuthenticationResult(result, outSecret.toByteArray())); } else { if (!this.config.isAllowPrivateKeyGeneration()) { return CompletableFuture.failedFuture(new IllegalArgumentException( "Private Key generation not enabled for environment " + environmentId)); } return createApplicationCertificateAndPrivateKey(applicationId, applicationNormalizedName, outSecret) .thenApply(result -> new CreateAuthenticationResult(result, outSecret.toByteArray())); } } @Override public void addRequiredKafkaProperties(Properties props) { props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SSL"); props.put(CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_CONFIG, "60000"); props.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, truststoreFile); props.put(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG, truststorePassword); props.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, caManager.getClientPkcs12File().getAbsolutePath()); props.put(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG, caManager.getClientPkcs12Password()); props.put(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, "PKCS12"); props.put(SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, ""); } @Override public String extractKafkaUserName(JSONObject existingAuthData) throws JSONException { return "User:" + existingAuthData.getString(DN); } @Override public CompletableFuture<CreateAuthenticationResult> createDeveloperAuthentication(String userName, JSONObject createParams) { ByteArrayOutputStream outSecret = new ByteArrayOutputStream(); return createDeveloperCertificateAndPrivateKey(userName, outSecret) .thenApply(result -> new CreateAuthenticationResult(result, outSecret.toByteArray())); } @Override public CompletableFuture<Void> deleteApplicationAuthentication(String applicationId, JSONObject existingAuthData) { // nothing to do here - enough to remove ACLs (done via update listener) return FutureUtil.noop(); } @Override public CompletableFuture<Void> deleteDeveloperAuthentication(String userName, JSONObject existingAuthData) { return FutureUtil.noop(); } private CompletableFuture<JSONObject> createApplicationCertificateFromCsr(String applicationId, String normalizedApplicationName, String csrData, String existingDn, OutputStream outputStreamForCerFile) { CompletableFuture<CertificateSignResult> future = existingDn != null ? caManager.extendApplicationCertificate(existingDn, csrData) : caManager.createApplicationCertificateFromCsr(applicationId, csrData, normalizedApplicationName); return future.thenCompose(result -> { try { outputStreamForCerFile.write(result.getCertificatePemData().getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { return CompletableFuture.failedFuture(e); } return CompletableFuture.completedFuture(result); }).thenApply(result -> toAuthJson(result)); } public CompletableFuture<CertificateSignResult> createDeveloperCertificateAndPrivateKey(String userName) { return caManager.createDeveloperCertificateAndPrivateKey(userName); } public boolean supportsDeveloperCertificates() { return caManager.supportsDeveloperCertificates(); } private CompletableFuture<JSONObject> createApplicationCertificateAndPrivateKey(String applicationId, String applicationNormalizedName, OutputStream outputStreamForP12File) { return caManager.createApplicationCertificateAndPrivateKey(applicationId, applicationNormalizedName) .thenCompose(result -> { try { outputStreamForP12File.write(result.getP12Data().orElse(new byte[0])); } catch (IOException e) { return CompletableFuture.failedFuture(e); } return CompletableFuture.completedFuture(toAuthJson(result)); }); } private CompletableFuture<JSONObject> createDeveloperCertificateAndPrivateKey(String userName, OutputStream outputStreamForP12File) { return caManager.createDeveloperCertificateAndPrivateKey(userName).thenCompose(result -> { try { outputStreamForP12File.write(result.getP12Data().orElse(new byte[0])); } catch (IOException e) { return CompletableFuture.failedFuture(e); } return CompletableFuture.completedFuture(toAuthJson(result)); }); } private void createDynamicTruststore() throws IOException, PKCSException { byte[] truststore = caManager.buildTrustStore(); File outFile = new File(config.getCertificatesWorkdir(), "kafka_" + environmentId + "_truststore.jks"); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(truststore); } this.truststoreFile = outFile.getAbsolutePath(); this.truststorePassword = "changeit"; } private JSONObject toAuthJson(CertificateSignResult result) { Instant expiresAt = Instant.ofEpochMilli(result.getCertificate().getNotAfter().getTime()); return new JSONObject(Map.of(DN, result.getDn(), EXPIRES_AT, expiresAt.toString())); } @Override public Optional<Instant> extractExpiryDate(JSONObject authData) { if (authData.has(EXPIRES_AT)) { return Optional.of(Instant.from(DateTimeFormatter.ISO_INSTANT.parse(authData.getString(EXPIRES_AT)))); } return Optional.empty(); } public static String getDnFromJson(JSONObject authData) { return authData.optString(DN); } }
10,956
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
CertificatesAuthenticationConfig.java
/FileExtraction/Java_unseen/HermesGermany_galapagos/src/main/java/com/hermesworld/ais/galapagos/certificates/auth/CertificatesAuthenticationConfig.java
package com.hermesworld.ais.galapagos.certificates.auth; import lombok.Getter; import lombok.Setter; import org.springframework.core.io.Resource; @Getter @Setter public class CertificatesAuthenticationConfig { private Resource caCertificateFile; private Resource caKeyFile; private String certificatesWorkdir; private String truststoreFile; private String truststorePassword; private String applicationCertificateValidity; private String developerCertificateValidity; private String clientDn; private boolean allowPrivateKeyGeneration; }
586
Java
.java
HermesGermany/galapagos
81
22
15
2020-10-02T09:40:40Z
2024-05-08T13:11:33Z
MLGammaDistribution.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/MLGammaDistribution.java
package de.unijena.bioinf.em; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.special.Gamma; public class MLGammaDistribution extends MLDistribution implements InterfaceMLDistribution { public MLGammaDistribution(boolean inverse, double shift ) { super(inverse, shift); // TODO Auto-generated constructor stub } public String getDescription(){ return "GammaDistribution"+(inverse?"Inverse":""); } public Map<String, Double> MStep(List<Double> expectation){ Map<String, Double> parameters=new HashMap<String, Double>(); double pi=EMUtils.getPi(expectation); parameters.put("pi", pi); double mu=EMUtils.getMu(sample, expectation); double logmu=EMUtils.getLogMu(sample, expectation); // double sd=EMUtils.getSD(sample, expectation,mu); // double n=EMUtils.getN(expectation); double s=Math.log(mu)-logmu; // double scale=Math.pow(sd,2)/mu; // double shape=mu/scale; // double shape=1/Math.pow(sd/mu,2)-1d/n; // double scale=mu/shape; double shape=Double.POSITIVE_INFINITY; double shape2=(3-s+Math.pow(Math.pow(s-3,2)+24*s,0.5))/(12*s); int it=0; while(it<500&&Math.abs(shape-shape2)>1E-13){ shape=shape2; shape2=shape-(Math.log(shape)-Gamma.digamma(shape)-s)/(1/shape-Gamma.trigamma(shape)); it++; } shape=shape2; double scale=mu/shape;//wikipedia if(Double.isInfinite(shape)){ System.out.println(); } parameters.put("scale", scale); parameters.put("shape",shape); return parameters; } @Override public double getNumericalMean(Map<String, Double> parameters) throws Exception { return new GammaDistribution(parameters.get("shape"), parameters.get("scale")).getNumericalMean(); } @Override public double getDensityUnprocessed(double x, Map<String, Double> parameters) throws Exception { return new GammaDistribution(parameters.get("shape"), parameters.get("scale")).density(x); } @Override public double getCumulativeProbabilityUnprocessed(double x1, Map<String, Double> parameters) throws Exception { return new GammaDistribution(parameters.get("shape"), parameters.get("scale")).cumulativeProbability(x1); } }
2,432
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MLLogisticDistribution.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/MLLogisticDistribution.java
package de.unijena.bioinf.em; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.distribution.LogisticDistribution; import org.apache.commons.math3.distribution.NormalDistribution; public class MLLogisticDistribution extends MLDistribution implements InterfaceMLDistribution { public MLLogisticDistribution(boolean inverse, double shift) { super(inverse, shift); // TODO Auto-generated constructor stub } public String getDescription(){ return "LogisticDistribution"+(inverse?"Inverse":""); } public Map<String, Double> MStep(List<Double> expectation){ Map<String, Double> parameters=new HashMap<String, Double>(); double pi=EMUtils.getPi(expectation); parameters.put("pi", pi); double mu=EMUtils.getMu(sample, expectation); parameters.put("mu",mu); double sd=EMUtils.getSD(sample, expectation, mu); double s=Math.pow(Math.pow(sd, 2)*3/Math.pow(Math.PI, 2),0.5); parameters.put("s", s); return parameters; } @Override public double getNumericalMean(Map<String, Double> parameters) throws Exception { return new LogisticDistribution(parameters.get("mu"), parameters.get("s")).getNumericalMean(); } @Override public double getDensityUnprocessed(double x, Map<String, Double> parameters) { return new LogisticDistribution(parameters.get("mu"), parameters.get("s")).density(x); } @Override public double getCumulativeProbabilityUnprocessed(double x1, Map<String, Double> parameters) { return new LogisticDistribution(parameters.get("mu"), parameters.get("s")).cumulativeProbability(x1); } }
1,683
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
EMMain.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/EMMain.java
package de.unijena.bioinf.em; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.Map.Entry; import org.apache.commons.math3.distribution.BetaDistribution; import org.apache.commons.math3.distribution.ExponentialDistribution; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.distribution.GumbelDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.WeibullDistribution; import de.unijena.bioinf.em.Sample.Type; import de.unijena.bioinf.statistics.MainStatistics; public class EMMain { static String R="C:\\Program Files\\R\\R-3.0.2\\bin\\RScript.exe"; static String EMScript="U:\\MSBlast\\EM.R"; static String base="U:\\MSBlast\\"; static InterfaceMLDistribution[] allDistributions=new InterfaceMLDistribution[]{ new MLNormalDistribution(false, 1E-5), // new MLLogNormalDistribution(false, 1E-5, false), // new MLLogNormalDistribution(true, 1E-5, false), // new MLBetaDistribution(false, 1E-5), // new MLBetaDistribution(true, 1E-5), new MLGammaDistribution(false, 1E-5), new MLGammaDistribution(true, 1E-5), new MLExponentialDistribution(false, 1E-5), new MLExponentialDistribution(true, 1E-5), new MLGumbelDistribution(false, 1E-5), new MLGumbelDistribution(true, 1E-5), new MLWeibullDistribution(false, 1E-5), new MLWeibullDistribution(true, 1E-5), new MLLogisticDistribution(false, 1E-5) }; static InterfaceMLDistribution[] selectedTPDistributions=new InterfaceMLDistribution[]{ new MLGammaDistribution(true, 1E-5), new MLGumbelDistribution(true, 1E-5), new MLWeibullDistribution(true, 1E-5) }; static InterfaceMLDistribution[] selectedFPDistributions=new InterfaceMLDistribution[]{ new MLGammaDistribution(false, 1E-5) }; static InterfaceMLDistribution[] selectedTPDistributions_LOG=new InterfaceMLDistribution[]{ new MLGammaDistribution(false, 1E-5), new MLGumbelDistribution(false, 1E-5), new MLWeibullDistribution(false, 1E-5), new MLNormalDistribution(false, 1E-5), new MLLogisticDistribution(false, 1E-5) }; static InterfaceMLDistribution[] selectedFPDistributions_LOG=new InterfaceMLDistribution[]{ new MLGammaDistribution(false, 1E-5), new MLWeibullDistribution(false, 1E-5) }; public static void main(String[] args) throws Exception{ // mainTest(); // mainReal("single"); mainReal("combined"); // getAllQValuesAverage(""); // mainReal("variable_component_mixture_model"); // getAllQValuesAverage("VCMM"); } public static void mainReal(String what) throws Exception{ int maxIterations=1000; double minChangeLikelihood=1E-20; // for(String compounds : new String[]{"Compounds","Selections"}){ for(String compounds : new String[]{"Compounds"}){ // for(boolean log:new boolean[]{false,true}){ for(boolean log:new boolean[]{false}){ boolean discardZeroEntries=log; BufferedWriter bw=new BufferedWriter(new FileWriter(base+"qValues_PEP_All"+compounds+"RPP\\EM_Likelihoods_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+what+".txt")); for(String comparisonMethod : new String[]{"MassBank", "CosineDistance"}){ // for(String comparisonMethod : new String[]{"MassBank"}){ for(String hs : new String[]{"DifferentMassesExcluded","DMEHighFDR"}){ // for(String hs : new String[]{"DifferentMassesExcluded"}){ for(String dataset : new String[]{"APFilesOriginal-GPFiles","APFilesOriginal-GPTrees","APTreesOriginal-GPTrees","OPFilesOriginal-GPFiles","OPFilesOriginal-GPTrees","OPTreesOriginal-GPTrees"}){ // for(String dataset : new String[]{"APFilesOriginal-GPFiles"}){ List<File> outputFilesQValuesPEP=new ArrayList<File>(); List<File> outputFilesQValuesEFDR=new ArrayList<File>(); int selMax=1; if(compounds.equals("Selections")){ selMax=10; } for(int sel=0;sel<selMax;sel++){ String add=""; if(compounds.equals("Selections")){ add="Selection"+sel+"_"; } File inputFile=new File(base+"qValues_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+hs+"_"+dataset+"RandomPeaks\\QValues_Selection"+sel+"_HitStatistic_"+hs+"_"+dataset+"RandomPeaks_1.hitlist"); if(!inputFile.exists())continue; List<Sample> sample_sep=EMUtils.getScores(inputFile, log, discardZeroEntries); if(what.contains("single")){ for(int i=0;i<sample_sep.size();i++){ List<EMResult> results=new ArrayList<EMResult>(); Sample sample=new Sample(sample_sep.get(i)); File outputFileData=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Single\\SampleData_"+add+(i==1?"TP":"FP")+"_"+hs+"_"+dataset+".txt"); EMUtils.writeData(outputFileData, sample.sample, null); for(InterfaceMLDistribution d:allDistributions){ System.out.println("processing "+compounds+" "+comparisonMethod+" "+add+" "+dataset+" "+hs+" "+" "+d.getDescription()+" "+(i==1?"TP":"FP")+ " log:"+log+" discardZeroEntries:"+discardZeroEntries+"..."); EM em=new EM(sample, d, maxIterations, minChangeLikelihood); try{ EMResult r=em.doEM(false); File outputFileDistribution=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Single\\Distribution_"+add+d.getDescription()+"_"+(i==1?"TP":"FP")+"_"+hs+"_"+dataset+".txt"); EMUtils.writeDistribution(outputFileDistribution, sample.sample, r.distributions, r.parameters); File outputFilePDF=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Single\\HistogramDistribution_"+add+d.getDescription()+"_"+(i==1?"TP":"FP")+"_"+hs+"_"+dataset+".pdf"); if(!outputFilePDF.getParentFile().exists())outputFilePDF.getParentFile().mkdirs(); String command="\""+R+"\" \""+EMScript+"\" "+outputFilePDF.getAbsolutePath()+" "+outputFileData.getAbsolutePath()+" "+outputFileDistribution.getAbsolutePath()+"\""; Process proc=Runtime.getRuntime().exec(command); System.out.println(r.likelihood); System.out.println(); if(!Double.isNaN(r.likelihood))results.add(r); }catch(Exception e){ System.err.println(e.getMessage() +" while proceeding "+ compounds+" "+comparisonMethod+" "+add+" "+dataset+" "+hs+" "+d.getDescription()+" "+(i==1?"TP":"FP")+ " log:"+log+" discardZeroEntries:"+discardZeroEntries); for(StackTraceElement el:e.getStackTrace()){ System.err.println(el.toString()); } } } Collections.sort(results); bw.write(compounds+" "+comparisonMethod+" "+dataset+" "+hs+" "+add+(i==1?"TP":"FP")+ " log:"+log+" discardZeroEntries:"+discardZeroEntries); bw.newLine(); for(EMResult r:results){ bw.write(r.toString()); bw.newLine(); bw.flush(); } bw.newLine(); } bw.newLine(); } if(what.contains("combined")){ Sample sample=new Sample(sample_sep); List<Double> qValuesReal=sample.getQValues(); List<EMResult> results=new ArrayList<EMResult>(); File outputFileData=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Combined\\SampleData_"+add+hs+"_"+dataset+".txt"); EMUtils.writeData(outputFileData, sample.sample, sample.types); InterfaceMLDistribution[] selectedFPDistributions_Tmp=(log?selectedFPDistributions_LOG:selectedFPDistributions); InterfaceMLDistribution[] selectedTPDistributions_Tmp=(log?selectedTPDistributions_LOG:selectedTPDistributions); for(InterfaceMLDistribution d1:selectedFPDistributions_Tmp){ for(InterfaceMLDistribution d2:selectedTPDistributions_Tmp){ // if(d1.getDescription().compareTo(d2.getDescription())>0)continue; System.out.println("processing "+compounds+" "+comparisonMethod+" "+add+" "+dataset+" "+hs+" "+d1.getDescription()+" "+d2.getDescription()+ " log:"+log+" discardZeroEntries:"+discardZeroEntries+"..."); List<InterfaceMLDistribution> distributions=new ArrayList<InterfaceMLDistribution>(); distributions.add(d1); distributions.add(d2); EM em=new EM(sample, distributions, maxIterations, minChangeLikelihood); try{ EMResult r=em.doEM(false); File outputFileDistribution=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Combined\\Distribution_"+add+hs+"_"+dataset+"_"+d1.getDescription()+"_"+d2.getDescription()+".txt"); EMUtils.writeDistribution(outputFileDistribution, sample.sample, r.distributions, r.parameters); File outputFilePDF_FP=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Combined\\HistogramDistribution_"+add+"FP_"+hs+"_"+dataset+"_"+d1.getDescription()+"_"+d2.getDescription()+".pdf"); File outputFilePDF_TP=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Combined\\HistogramDistribution_"+add+"TP_"+hs+"_"+dataset+"_"+d1.getDescription()+"_"+d2.getDescription()+".pdf"); File outputFilePDF=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Combined\\HistogramDistribution_"+add+hs+"_"+dataset+"_"+d1.getDescription()+"_"+d2.getDescription()+".pdf"); if(!outputFilePDF.getParentFile().exists())outputFilePDF.getParentFile().mkdirs(); String command="\""+R+"\" \""+EMScript+"\" "+outputFilePDF.getAbsolutePath()+" "+outputFileData.getAbsolutePath()+" "+outputFileDistribution.getAbsolutePath()+" "+outputFilePDF_FP.getAbsolutePath()+" "+outputFilePDF_TP.getAbsolutePath()+"\""; Process proc=Runtime.getRuntime().exec(command); List<Double> qValuesPred=r.getQValuesByPEP(); r.deviation_QValuesByPEP=EMUtils.deviation(qValuesReal,qValuesPred); File outputFileQValues=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"PEP\\QValues_HitStatistic_"+add+hs+"_"+dataset+"_"+d1.getDescription()+"_"+d2.getDescription()+".txt"); EMUtils.writeQValues(outputFileQValues, r.toString(), qValuesReal, qValuesPred); qValuesPred=r.getQValuesByEDFR(); r.deviation_QValuesByEFDR=EMUtils.deviation(qValuesReal,qValuesPred); outputFileQValues=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"EFDR\\QValues_HitStatistic_"+add+hs+"_"+dataset+"_"+d1.getDescription()+"_"+d2.getDescription()+".txt"); EMUtils.writeQValues(outputFileQValues, r.toString(), qValuesReal, qValuesPred); for(int bins:new int[]{10,20,30}){ Map<Type,List<Double>> pValuesPredMap=r.getPValues(sample); List<Double> pValuesPred=new ArrayList<Double>(); pValuesPred.addAll(pValuesPredMap.get(Type.FalsePositiveMatch)); pValuesPred.addAll(pValuesPredMap.get(Type.TruePositiveMatch)); File outputFilePValuesAll=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"PValues\\QValues_HitStatistic_"+add+hs+"_"+dataset+"_"+d1.getDescription()+"_"+d2.getDescription()+"_All_"+bins+"bins.txt"); EMUtils.writePValues(outputFilePValuesAll, r.toString()+" All", pValuesPred, bins); File outputFilePValuesFP=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"PValues\\QValues_HitStatistic_"+add+hs+"_"+dataset+"_"+d1.getDescription()+"_"+d2.getDescription()+"_FP_"+bins+"bins.txt"); EMUtils.writePValues(outputFilePValuesFP, r.toString()+" FP", pValuesPredMap.get(Type.FalsePositiveMatch), bins); File outputFilePValuesTP=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"PValues\\QValues_HitStatistic_"+add+hs+"_"+dataset+"_"+d1.getDescription()+"_"+d2.getDescription()+"_TP_"+bins+"bins.txt"); EMUtils.writePValues(outputFilePValuesTP, r.toString()+" TP", pValuesPredMap.get(Type.TruePositiveMatch), bins); } System.out.println(r.likelihood+" "+r.deviation_QValuesByPEP+" "+r.deviation_QValuesByEFDR); System.out.println(); if(!Double.isNaN(r.likelihood))results.add(r); }catch(Exception e){ System.err.println(e.getMessage() +" while proceeding "+ compounds+" "+comparisonMethod+" "+add+" "+dataset+" "+hs+" "+d1.getDescription()+" "+d2.getDescription()+ " log:"+log+" discardZeroEntries:"+discardZeroEntries); for(StackTraceElement el:e.getStackTrace()){ System.err.println(el.toString()); } } } } Collections.sort(results); bw.write(compounds+" "+comparisonMethod+" "+add+" "+dataset+" "+hs+ " log:"+log+" discardZeroEntries:"+discardZeroEntries); bw.newLine(); for(EMResult r:results){ bw.write(r.toString()); bw.newLine(); bw.flush(); } bw.newLine(); EMResult r=results.get(0); File outputFileDistribution=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Combined\\Distribution_"+add+hs+"_"+dataset+".txt"); EMUtils.writeDistribution(outputFileDistribution, sample.sample, r.distributions, r.parameters); File outputFilePDF_FP=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Combined\\HistogramDistribution_"+add+"FP_"+hs+"_"+dataset+".pdf"); File outputFilePDF_TP=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Combined\\HistogramDistribution_"+add+"TP_"+hs+"_"+dataset+".pdf"); File outputFilePDF=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"Combined\\HistogramDistribution_"+add+hs+"_"+dataset+".pdf"); String command="\""+R+"\" \""+EMScript+"\" "+outputFilePDF.getAbsolutePath()+" "+outputFileData.getAbsolutePath()+" "+outputFileDistribution.getAbsolutePath()+" "+outputFilePDF_FP.getAbsolutePath()+" "+outputFilePDF_TP.getAbsolutePath()+"\""; Process proc=Runtime.getRuntime().exec(command); List<Double> qValuesPred=r.getQValuesByPEP(); File outputFileQValues=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"PEP\\QValues_HitStatistic_"+add+hs+"_"+dataset+"PEP.qValueMeanAverage"); outputFilesQValuesPEP.add(outputFileQValues); EMUtils.writeQValues(outputFileQValues, r.toString(), qValuesReal, qValuesPred); qValuesPred=r.getQValuesByEDFR(); outputFileQValues=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"EFDR\\QValues_HitStatistic_"+add+hs+"_"+dataset+"EFDR.qValueMeanAverage"); outputFilesQValuesEFDR.add(outputFileQValues); EMUtils.writeQValues(outputFileQValues, r.toString(), qValuesReal, qValuesPred); for(int bins:new int[]{10,20,30}){ Map<Type,List<Double>> pValuesPredMap=r.getPValues(sample); List<Double> pValuesPred=new ArrayList<Double>(); pValuesPred.addAll(pValuesPredMap.get(Type.FalsePositiveMatch)); pValuesPred.addAll(pValuesPredMap.get(Type.TruePositiveMatch)); File outputFilePValuesAll=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"PValues\\QValues_HitStatistic_"+add+hs+"_"+dataset+"_All_"+bins+"bins.txt"); EMUtils.writePValues(outputFilePValuesAll, r.toString()+" All", pValuesPred, bins); File outputFilePValuesFP=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"PValues\\QValues_HitStatistic_"+add+hs+"_"+dataset+"_FP_"+bins+"bins.txt"); EMUtils.writePValues(outputFilePValuesFP, r.toString()+" FP", pValuesPredMap.get(Type.FalsePositiveMatch), bins); File outputFilePValuesTP=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"PValues\\QValues_HitStatistic_"+add+hs+"_"+dataset+"_TP_"+bins+"bins.txt"); EMUtils.writePValues(outputFilePValuesTP, r.toString()+" TP", pValuesPredMap.get(Type.TruePositiveMatch), bins); } } if(what.contains("variable_component_mixture_model")){ Sample sample=new Sample(sample_sep); List<Double> qValuesReal=sample.getQValues(); File outputFileData=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+add+hs+"_"+dataset+"CombinedVCMM\\SampleData_"+hs+"_"+dataset+".txt"); EMUtils.writeData(outputFileData, sample.sample, null); System.out.println("processing "+compounds+" "+comparisonMethod+" "+add+" "+dataset+" "+hs+ " log:"+log+" discardZeroEntries:"+discardZeroEntries+" variable component mixture model..."); List<InterfaceMLDistribution> distributions=new ArrayList<InterfaceMLDistribution>(); for(int i=0;i<20;i++){ distributions.add(new MLNormalDistribution(false,0)); } EM em=new EM(sample, distributions, maxIterations, minChangeLikelihood); try{ EMResult r=em.doEM(true); File outputFileDistribution=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+add+hs+"_"+dataset+"CombinedVCMM\\Distribution_"+hs+"_"+dataset+".txt"); EMUtils.writeDistribution(outputFileDistribution, sample.sample, r.distributions, r.parameters); File outputFilePDF=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+add+hs+"_"+dataset+"CombinedVCMM\\HistogramDistribution_"+hs+"_"+dataset+".pdf"); if(!outputFilePDF.getParentFile().exists())outputFilePDF.getParentFile().mkdirs(); String command="\""+R+"\" \""+EMScript+"\" "+outputFilePDF.getAbsolutePath()+" "+outputFileData.getAbsolutePath()+" "+outputFileDistribution.getAbsolutePath()+"\""; Process proc=Runtime.getRuntime().exec(command); List<Double> qValuesPred=r.getQValuesByPEP(); r.deviation_QValuesByPEP=EMUtils.deviation(qValuesReal,qValuesPred); File outputFileQValues=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+add+hs+"_"+dataset+"PEPVCMM\\QValues_HitStatistic_"+hs+"_"+dataset+"PEPVCMM.qValueMeanAverage"); outputFilesQValuesPEP.add(outputFileQValues); EMUtils.writeQValues(outputFileQValues, r.toString(), qValuesReal, qValuesPred); qValuesPred=r.getQValuesByEDFR(); r.deviation_QValuesByEFDR=EMUtils.deviation(qValuesReal,qValuesPred); outputFileQValues=new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+add+hs+"_"+dataset+"EFDRVCMM\\QValues_HitStatistic_"+hs+"_"+dataset+"EFDRVCMM.qValueMeanAverage"); outputFilesQValuesEFDR.add(outputFileQValues); EMUtils.writeQValues(outputFileQValues, r.toString(), qValuesReal, qValuesPred); System.out.println(r.likelihood+" "+r.deviation_QValuesByPEP+" "+r.deviation_QValuesByEFDR); System.out.println(); if(!Double.isNaN(r.likelihood)){ bw.write(compounds+" "+comparisonMethod+" "+add+" "+dataset+" "+hs+ " log:"+log+" discardZeroEntries:"+discardZeroEntries); bw.newLine(); bw.write(r.toString()); bw.newLine(); bw.flush(); bw.newLine(); } }catch(Exception e){ System.err.println(e.getMessage() +" while proceeding "+ compounds+" "+comparisonMethod+" "+add+" "+dataset+" "+hs+" variable component mixture model"); for(StackTraceElement el:e.getStackTrace()){ System.err.println(el.toString()); } } } } bw.newLine(); if(compounds.equals("Selections")&&(what.contains("combined")||what.contains("variable_component_mixture_model"))){ String add=""; if(what.contains("variable_component_mixture_model"))add="VCMM"; getQValuesAverage(outputFilesQValuesPEP, new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"PEP"+add+"\\QValues_HitStatistic_"+hs+"_"+dataset+"PEP"+add+".qValueMeanAverage")); getQValuesAverage(outputFilesQValuesEFDR, new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+(discardZeroEntries?"DZE_":"")+(log?"Log_":"")+hs+"_"+dataset+"EFDR"+add+"\\QValues_HitStatistic_"+hs+"_"+dataset+"EFDR"+add+".qValueMeanAverage")); } // } // bw.newLine(); } bw.newLine(); } bw.newLine(); } bw.newLine(); bw.close(); } } } private static void getStandardOutput(Process proc) throws IOException { BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); // read the output from the command System.out.println("Here is the standard output of the command:\n"); String s = null; while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command System.out.println("Here is the standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } } public static void mainTest() throws Exception{ int maxIterations=10000; List<List<Double>> sample_sep=EMUtils.getSimulatedScores(new int[]{1000,2000},Arrays.asList(new RealDistribution[]{ new BetaDistribution(2,2), new BetaDistribution(5,1) })); // List<List<Double>> sample_sep=EMUtils.getSimulatedScores(new int[]{1000,2000},Arrays.asList(new RealDistribution[]{ // new GammaDistribution(2,2), // new GammaDistribution(7.5,1) // })); List<Double> values=new ArrayList<Double>(); List<InterfaceMLDistribution> distributions=new ArrayList<InterfaceMLDistribution>(); for(List<Double> s:sample_sep){ values.addAll(s); distributions.add(new MLBetaDistribution(false, 0)); // distributions.add(new MLGammaDistribution(false, 0)); } Sample sample=new Sample(values, null, null); // EM em=new EM(sample, distributions, maxIterations, minChangeLikelihood); EM em=new EM(sample, distributions, maxIterations, Double.NEGATIVE_INFINITY); EMResult r=em.doEM(true); System.out.println(r.likelihood); } public static void getAllQValuesAverage(String type) throws Exception{ for(String compounds : new String[]{"Selections"}){ for(String comparisonMethod : new String[]{"MassBank", "CosineDistance"}){ // for(String comparisonMethod : new String[]{"MassBank"}){ for(String hs : new String[]{"DifferentMassesExcluded","DMEHighFDR"}){ // for(String hs : new String[]{"DifferentMassesExcluded"}){ for(String dataset : new String[]{"APFilesOriginal-GPFiles","APFilesOriginal-GPTrees","APTreesOriginal-GPTrees","OPFilesOriginal-GPFiles","OPFilesOriginal-GPTrees","OPTreesOriginal-GPTrees"}){ // for(String dataset : new String[]{"APFilesOriginal-GPFiles"}){ List<File> outputFilesQValuesPEP=new ArrayList<File>(); List<File> outputFilesQValuesEFDR=new ArrayList<File>(); int selMax=0; if(compounds.equals("Selections")){ selMax=10; } for(int sel=0;sel<selMax;sel++){ String add=""; if(compounds.equals("Selections")){ add="Selection"+sel+"_"; } outputFilesQValuesPEP.add(new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+hs+"_"+dataset+"PEP"+type+"\\QValues_HitStatistic_"+add+hs+"_"+dataset+"PEP"+type+".qValueMeanAverage")); outputFilesQValuesEFDR.add(new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+hs+"_"+dataset+"EFDR"+type+"\\QValues_HitStatistic_"+add+hs+"_"+dataset+"EFDR"+type+".qValueMeanAverage")); } getQValuesAverage(outputFilesQValuesPEP, new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+hs+"_"+dataset+"PEP"+type+"\\QValues_HitStatistic_"+hs+"_"+dataset+"PEP"+type+".qValueMeanAverage")); getQValuesAverage(outputFilesQValuesEFDR, new File(base+"qValues_PEP_All"+compounds+"RPP\\pos\\"+comparisonMethod+"\\HitStatistic_"+hs+"_"+dataset+"EFDR"+type+"\\QValues_HitStatistic_"+hs+"_"+dataset+"EFDR"+type+".qValueMeanAverage")); } } } } } private static void getQValuesAverage(List<File> inputFiles, File outputFile) throws Exception{ List<List<double[]>> r=MainStatistics.getPoints(inputFiles, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, true, true, "and", false, false); Set<Double> keys=new TreeSet<Double>(); for(List<double[]> dl:r){ for(double d[]:dl){ keys.add(d[0]); } } List<double[]> res=new ArrayList<double[]>(); List<List<Double>> p=new ArrayList<List<Double>>(); for(double k:keys){ List<Double> points=new ArrayList<Double>(); for(List<double[]> dl:r){ for(int i=1;i<dl.size();i++){ double k_i=dl.get(i-1)[0]; double v_i=dl.get(i-1)[1]; double k_j=dl.get(i)[0]; double v_j=dl.get(i)[1]; if(k_i==k_j)continue; if(k_j>=k){ double m=(v_i-v_j)/(k_i-k_j); double n=v_i-m*k_i; points.add(m*k+n); break; } if(i==dl.size()-1){ points.add(v_j); } } } // for(double d:points)System.out.println(d); // System.out.println(); double[] as=MainStatistics.getAverageAndStandardDeviation(points); p.add(points); res.add(new double[]{k,as[0],as[1]}); } BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); for(int i=0;i<inputFiles.size();i++){ File f=inputFiles.get(i); BufferedReader br=new BufferedReader(new FileReader(f)); if(i!=0)bw.write("\t"); bw.write(f.getName()+": " + br.readLine()); br.close(); } bw.newLine(); bw.write("calculated qValue\testimated qValue\tstandard deviation\tall values"); bw.newLine(); for(int i=0;i<res.size();i++){ double[] entry=res.get(i); List<Double> entryPoints=p.get(i); bw.write(entry[0]+"\t"+entry[1]+"\t"+entry[2]+"\t"); for(int j=0;j<entryPoints.size();j++){ double d=entryPoints.get(j); bw.write(d+""); if(j!=entryPoints.size()-1)bw.write(","); } bw.newLine(); } bw.close(); } }
29,660
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MLDistribution.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/MLDistribution.java
package de.unijena.bioinf.em; import java.util.ArrayList; import java.util.List; import java.util.Map; public abstract class MLDistribution implements InterfaceMLDistribution{ public double shift=+1E-5; static double borders=+1E-4; public boolean inverse=false; public Double inverse_x=null; public Double max_sample_value=null; public Double min_sample_value=null; public List<Double> sample_original=null; public List<Double> sample; public MLDistribution(boolean inverse, double shift){ this.inverse=inverse; this.shift=shift; } @Override public List<Double> EStep(Map<String,Double> parameters) throws Exception{ List<Double> expectation=new ArrayList<Double>(); for(int i=0;i<sample.size();i++){ double x=sample.get(i); double value=parameters.get("pi")*getDensityUnprocessed(x,parameters); expectation.add(value); } return expectation; } @Override public void preprocessSample(List<Double> sample_final){ sample_original=sample_final; this.sample=new ArrayList<Double>(); List<Double> sample_tmp=new ArrayList<Double>(); if(!inverse){ sample_tmp.addAll(sample_final); }else{ double max=Double.NEGATIVE_INFINITY; for(Double d:sample_final){ max=Math.max(max, d); } inverse_x=max; for(Double d:sample_final){ sample_tmp.add(max-d); } } max_sample_value=Double.NEGATIVE_INFINITY; min_sample_value=Double.POSITIVE_INFINITY; for(double s:sample_tmp){ double s_tmp=s+shift; sample.add(s_tmp); max_sample_value=Math.max(max_sample_value, s_tmp); min_sample_value=Math.min(min_sample_value, s_tmp); } } @Override public double getDensity(double x, Map<String, Double> parameters) throws Exception { if(inverse) x=inverse_x-x; x+=shift; return getDensityUnprocessed(x,parameters); } @Override public double getProbability(double x, Map<String, Double> parameters) throws Exception { if(inverse) x=inverse_x-x; x+=shift; double y=max_sample_value+borders; if(inverse){ y=x; x=min_sample_value-borders; } double result=getCumulativeProbabilityUnprocessed(y,parameters)-getCumulativeProbabilityUnprocessed(x,parameters); return result; } }
2,275
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
EMResult.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/EMResult.java
package de.unijena.bioinf.em; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import de.unijena.bioinf.em.Sample.Type; class EMResult implements Comparable<EMResult>{ List<Map<String, Double>> parameters; final List<List<Double>> expectations; List<InterfaceMLDistribution> distributions; final List<Double> values; double likelihood; public Double deviation_QValuesByEFDR=null; public Double deviation_QValuesByPEP=null; public EMResult(List<Double> values, List<List<Double>> expectations, List<InterfaceMLDistribution> distributions, List<Map<String, Double>> parameters, double likelihood){ this.distributions=distributions; this.parameters=parameters; this.likelihood=likelihood; this.expectations=expectations; this.values=new ArrayList<Double>(); this.values.addAll(values); } @Override public int compareTo(EMResult o) { return Double.compare(o.likelihood,this.likelihood); } public String toString(){ String description=""; description+=likelihood; description+="\t"+deviation_QValuesByPEP; description+="\t"+deviation_QValuesByEFDR; TreeMap<Double, List<Integer>> means=new TreeMap<Double,List<Integer>>(); for(int i=0;i<distributions.size();i++){ InterfaceMLDistribution d=distributions.get(i); Map<String, Double> p=parameters.get(i); Double mean=Double.NaN; try{ mean=d.getNumericalMean(p); }catch(Exception e){} if(!means.containsKey(mean))means.put(mean,new ArrayList<Integer>()); means.get(mean).add(i); } for(List<Integer> iList:means.values()){ for(int i:iList){ InterfaceMLDistribution d=distributions.get(i); Map<String, Double> p=parameters.get(i); description+="\t"+d.getDescription()+":"; for(Entry<String, Double> e:p.entrySet()){ description+=" "+e.getKey()+"="+e.getValue(); } } } return description; } public List<Double> getEFDRs() throws Exception{ List<Double> fdrs=new ArrayList<Double>(); boolean[] FPs = getFPIndizes(); List<List<Double>> sortedExpectations=getSortedExpectationsByValue(values, this.expectations); double sum=0; double n=0; for(int j=0;j<sortedExpectations.get(0).size();j++){ for(int i=0;i<FPs.length;i++){ boolean FP=FPs[i]; double e=sortedExpectations.get(i).get(j); if(FP)sum+=e; n+=e; } fdrs.add(sum/n); } return fdrs; } public List<Double> getFDRsByPEP() throws Exception{ List<Double> fdrs=new ArrayList<Double>(); boolean[] FPs = getFPIndizes(); List<Double> sortedValues=new ArrayList<Double>(); sortedValues.addAll(values); Collections.sort(sortedValues,Collections.reverseOrder()); for(int j=0;j<sortedValues.size();j++){ double fpProb=0; double tpProb=0; double v=sortedValues.get(j); for(int i=0;i<FPs.length;i++){ boolean FP=FPs[i]; double e=distributions.get(i).getProbability(v, parameters.get(i)); e*=parameters.get(i).get("pi"); if(FP)fpProb+=e; else tpProb+=e; } fdrs.add(fpProb/(fpProb+tpProb)); } return fdrs; } public Map<Type,List<Double>> getPValues(Sample sample) throws Exception{ Map<Type,List<Double>> result=new HashMap<Type,List<Double>>(); boolean[] FPs = getFPIndizes(); for(int j=0;j<sample.sample.size();j++){ double fpSum=0; double v=sample.sample.get(j); Type t=sample.types.get(j); for(int i=0;i<FPs.length;i++){ boolean FP=FPs[i]; if(!FP)continue; double e=distributions.get(i).getProbability(v, parameters.get(i)); e/=distributions.get(i).getProbability(Double.NEGATIVE_INFINITY, parameters.get(i)); fpSum+=e; } if(!result.containsKey(t))result.put(t,new ArrayList<Double>()); result.get(t).add(fpSum); } return result; } public List<Double> getQValuesByEDFR() throws Exception{ List<Double> fdrs=getEFDRs(); for(int i=fdrs.size()-2;i>=0;i--){ fdrs.set(i,Math.min(fdrs.get(i+1), fdrs.get(i))); } return fdrs; } public List<Double> getQValuesByPEP() throws Exception{ List<Double> fdrs=getFDRsByPEP(); for(int i=fdrs.size()-2;i>=0;i--){ fdrs.set(i,Math.min(fdrs.get(i+1), fdrs.get(i))); } return fdrs; } public List<List<Double>> getSortedExpectationsByValue(List<Double> values, List<List<Double>> expectations){ List<Double> values_tmp=new ArrayList<Double>(); values_tmp.addAll(values); List<List<Double>> expectations_tmp=new ArrayList<List<Double>>(); for(List<Double> e:expectations){ List<Double> e_tmp=new ArrayList<Double>(); e_tmp.addAll(e); expectations_tmp.add(e_tmp); } for(int i=0;i<values_tmp.size()-1;i++){ double maxValue=Integer.MIN_VALUE; int maxIndex=Integer.MAX_VALUE; for(int j=i;j<values_tmp.size();j++){ if(values_tmp.get(j)>maxValue){ maxValue=values_tmp.get(j); maxIndex=j; } } change(i,maxIndex, values_tmp); for(List<Double> e:expectations_tmp){ change(i,maxIndex, e); } } return expectations_tmp; } public boolean[] getFPIndizes() throws Exception{ double minMean=Double.POSITIVE_INFINITY; int minIndex=-1; double maxMean=Double.NEGATIVE_INFINITY; int maxIndex=-1; boolean[] FPs=new boolean[parameters.size()]; for(int i=0;i<parameters.size();i++){ double mean=distributions.get(i).getNumericalMean(parameters.get(i)); if(mean<0.5)FPs[i]=true; else FPs[i]=false; if(minMean>mean){ minMean=mean; minIndex=i; } if(maxMean<mean){ maxMean=mean; maxIndex=i; } } FPs[minIndex]=true; FPs[maxIndex]=false; return FPs; } public static void change(int i, int j, List list){ Object o=list.get(i); list.set(i,list.get(j)); list.set(j, o); } }
5,949
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
InterfaceMLDistribution.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/InterfaceMLDistribution.java
package de.unijena.bioinf.em; import java.util.ArrayList; import java.util.List; import java.util.Map; public interface InterfaceMLDistribution { public Map<String, Double> MStep(List<Double> expectation); public List<Double> EStep(Map<String, Double> parameters) throws Exception; double getDensity(double x, Map<String, Double> parameters) throws Exception; public double getDensityUnprocessed(double x, Map<String, Double> parameters) throws Exception; public String getDescription(); public void preprocessSample(List<Double> sample); double getProbability(double x, Map<String, Double> parameters) throws Exception; double getCumulativeProbabilityUnprocessed(double x, Map<String, Double> parameters) throws Exception; double getNumericalMean(Map<String, Double> parameters) throws Exception; }
835
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MLWeibullDistribution.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/MLWeibullDistribution.java
package de.unijena.bioinf.em; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.distribution.WeibullDistribution; import org.apache.commons.math3.special.Gamma; import umontreal.iro.lecuyer.probdist.WeibullDist; public class MLWeibullDistribution extends MLDistribution implements InterfaceMLDistribution { public MLWeibullDistribution(boolean inverse, double shift) { super(inverse, shift); // TODO Auto-generated constructor stub } public String getDescription(){ return "WeibullDistribution"+(inverse?"Inverse":""); } public Map<String, Double> MStep(List<Double> expectation){ Map<String, Double> parameters=new HashMap<String, Double>(); double pi=EMUtils.getPi(expectation); parameters.put("pi", pi); double ZLogX=getZLogX(sample, expectation); double Z=getZ(expectation); double alpha2=parameters.containsKey("alpha")?parameters.get("alpha"):1; double alpha=Double.POSITIVE_INFINITY; int it=0; while(it<2000&&Math.abs(alpha-alpha2)>1E-7){ alpha=alpha2; double ZXAlphaLogX=getZXAlphaLogX(sample, expectation, alpha); double ZXAlpha=getZXAlpha(sample, expectation, alpha); double ZXAlphaLogX2=getZXAlphaLogX2(sample, expectation, alpha); double fn=ZLogX/Z+1/alpha-ZXAlphaLogX/ZXAlpha; double dfn=(1+Math.pow(alpha, 2))+(ZXAlpha*ZXAlphaLogX2-Math.pow(ZXAlphaLogX, 2))/Math.pow(ZXAlpha, 2); alpha2=alpha+fn/dfn; it++; } alpha=alpha2; parameters.put("alpha", alpha); double ZXAlpha=getZXAlpha(sample, expectation, alpha); double lambda=Math.pow(ZXAlpha/Z,1/alpha); parameters.put("lambda", lambda); return parameters; } public static double getZXAlpha(List<Double> sample, List<Double> expectation, double alpha){ double mu=0; for(int j=0;j<expectation.size();j++){ double e=expectation.get(j); double x=sample.get(j); mu+=e*Math.pow(x, alpha); } return mu; } public static double getZXAlphaLogX2(List<Double> sample, List<Double> expectation, double alpha){ double mu=0; for(int j=0;j<expectation.size();j++){ double e=expectation.get(j); double x=sample.get(j); mu+=e*Math.pow(x, alpha)*Math.pow(Math.log(x),2); } return mu; } public static double getZXAlphaLogX(List<Double> sample, List<Double> expectation, double alpha){ double mu=0; for(int j=0;j<expectation.size();j++){ double e=expectation.get(j); double x=sample.get(j); mu+=e*Math.pow(x, alpha)*Math.log(x); } return mu; } public static double getZLogX(List<Double> sample, List<Double> expectation){ double mu=0; for(int j=0;j<expectation.size();j++){ double e=expectation.get(j); double x=sample.get(j); mu+=e*Math.log(x); } return mu; } public static double getZ(List<Double> expectation){ double mu=0; for(int j=0;j<expectation.size();j++){ double e=expectation.get(j); mu+=e; } return mu; } @Override public double getNumericalMean(Map<String, Double> parameters) throws Exception { return new WeibullDistribution(parameters.get("alpha"), parameters.get("lambda")).getNumericalMean(); } @Override public double getDensityUnprocessed(double x, Map<String, Double> parameters) throws Exception { return new WeibullDistribution(parameters.get("alpha"), parameters.get("lambda")).density(x); } @Override public double getCumulativeProbabilityUnprocessed(double x1, Map<String, Double> parameters) throws Exception { return new WeibullDistribution(parameters.get("alpha"), parameters.get("lambda")).cumulativeProbability(x1); } }
3,684
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MLLogNormalDistribution.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/MLLogNormalDistribution.java
package de.unijena.bioinf.em; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.distribution.LogNormalDistribution; import org.apache.commons.math3.distribution.NormalDistribution; public class MLLogNormalDistribution extends MLDistribution implements InterfaceMLDistribution { public MLLogNormalDistribution(boolean inverse, double shift) { super(inverse, shift); // TODO Auto-generated constructor stub } public String getDescription(){ return "LogNormalDistribution"+(inverse?"Inverse":""); } public Map<String, Double> MStep(List<Double> expectation){ Map<String, Double> parameters=new HashMap<String, Double>(); double pi=EMUtils.getPi(expectation); parameters.put("pi", pi); double mu=EMUtils.getLogMu(sample, expectation); parameters.put("mu",mu); double sd=EMUtils.getLogSD(sample, expectation, mu); parameters.put("sd", Math.max(1E-10,sd)); return parameters; } @Override public double getNumericalMean(Map<String, Double> parameters) throws Exception { return new LogNormalDistribution(parameters.get("mu"), parameters.get("sd")).getNumericalMean(); } @Override public double getDensityUnprocessed(double x, Map<String, Double> parameters) { return new LogNormalDistribution(parameters.get("mu"), parameters.get("sd")).density(x); } @Override public double getCumulativeProbabilityUnprocessed(double x1, Map<String, Double> parameters) { return new LogNormalDistribution(parameters.get("mu"), parameters.get("sd")).cumulativeProbability(x1); } }
1,653
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
EMUtils.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/EMUtils.java
package de.unijena.bioinf.em; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.TreeSet; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.distribution.RealDistribution; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.statistics.HistogramDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.XYDataset; import de.unijena.bioinf.em.Sample.Type; public class EMUtils { public static void normalizeExpectations(List<List<Double>> expectations){ for(int i=0;i<expectations.get(0).size();i++){ double sum=0; for(int j=0;j<expectations.size();j++){ sum+=expectations.get(j).get(i); } for(int j=0;j<expectations.size();j++){ if(sum==0)expectations.get(j).set(i,0d); else expectations.get(j).set(i,expectations.get(j).get(i)/sum); } } } public static double getLogLikelihood(List<InterfaceMLDistribution> distributions, List<Map<String, Double>> parameters) throws Exception{ List<List<Double>> expectations=EStepWithoutNormalization(distributions,parameters); double sum=0; for(int i=0;i<expectations.get(0).size();i++){ double sumTmp=0; for(int j=0;j<expectations.size();j++){ sumTmp+=expectations.get(j).get(i); } if(sumTmp!=0)sum+=Math.log(sumTmp); } return sum; } public static List<Map<String, Double>> MStep(List<InterfaceMLDistribution> distributions, List<List<Double>> expectations){ List<Map<String, Double>> parameters=new ArrayList<Map<String, Double>>(); for(int i=0;i<expectations.size();i++){ parameters.add(distributions.get(i).MStep(expectations.get(i))); } return parameters; } private static List<List<Double>> EStepWithoutNormalization(List<InterfaceMLDistribution> distributions, List<Map<String,Double>> parameters) throws Exception{ List<List<Double>> expectations=new ArrayList<List<Double>>(); for(int i=0;i<parameters.size();i++){ expectations.add(distributions.get(i).EStep(parameters.get(i))); } return expectations; } public static List<List<Double>> EStep(List<InterfaceMLDistribution> distributions, List<Map<String,Double>> parameters) throws Exception{ List<List<Double>> expectations=EStepWithoutNormalization(distributions,parameters); normalizeExpectations(expectations); return expectations; } public static List<List<Double>> initializeRandomExpectations(int numberSamples, int numberDistributions){ List<List<Double>> expectations=new ArrayList<List<Double>>(); Random r=new Random(); for(int n=0;n<numberDistributions;n++){ List<Double> expectation=new ArrayList<Double>(); expectations.add(expectation); for(int i=0;i<numberSamples;i++){ expectation.add(r.nextDouble()); } } normalizeExpectations(expectations); return expectations; } public static double getPi(List<Double> expectation){ double piDividend=0; double piDivisor=0; for(double e:expectation){ piDividend+=e; piDivisor++; } double pi=piDividend/piDivisor; return pi; } static public double[] getArrayOfValues(List<Double> sample){ double[] tmp=new double[sample.size()]; for(int i=0;i<tmp.length;i++){ tmp[i]=sample.get(i); } return tmp; } public static double getMu(List<Double> sample, List<Double> expectation){ double muDividend=0; double muDivisor=0; for(int j=0;j<expectation.size();j++){ double e=expectation.get(j); double x=sample.get(j); muDividend+=e*x; muDivisor+=e; } double mu=muDividend/muDivisor; return mu; } public static double deviation(List<Double> d1, List<Double> d2){ double sum=0; for(int i=0;i<d1.size();i++){ sum+=Math.abs(Math.pow(d1.get(i)-d2.get(i),2)); } return sum/d1.size(); } public static double getLogMu(List<Double> sample, List<Double> expectation){ double muDividend=0; double muDivisor=0; for(int j=0;j<expectation.size();j++){ double e=expectation.get(j); double x=sample.get(j); muDividend+=e*Math.log(x); muDivisor+=e; } double mu=muDividend/muDivisor; return mu; } public static double getSD(List<Double> sample, List<Double> expectation, Double mu){ double sdDividend=0; double sdDivisor=0; if(mu==null)mu=getMu(sample, expectation); for(int j=0;j<expectation.size();j++){ double e=expectation.get(j); double x=sample.get(j); sdDividend+=e*Math.pow(x-mu,2); sdDivisor+=e; } double sd=Math.pow(sdDividend/sdDivisor,0.5); return sd; } public static double getLogSD(List<Double> sample, List<Double> expectation, Double mu){ double sdDividend=0; double sdDivisor=0; if(mu==null)mu=getLogMu(sample, expectation); for(int j=0;j<expectation.size();j++){ double e=expectation.get(j); double x=sample.get(j); sdDividend+=e*Math.pow(Math.log(x)-mu,2); sdDivisor+=e; } double sd=Math.pow(sdDividend/sdDivisor,0.5); return sd; } public static double getN(List<Double> expectation){ double n=0; for(int j=0;j<expectation.size();j++){ double e=expectation.get(j); n+=e; } return n; } public static List<Sample> getScores(File inputFile, boolean log, boolean discardZeroEntries) throws Exception{ Sample TPs=new Sample(); Sample FPs=new Sample(); List<Sample> all=new ArrayList<Sample>(); all.add(FPs); all.add(TPs); BufferedReader br=new BufferedReader(new FileReader(inputFile)); br.readLine(); br.readLine(); String line; int i=0; double minValue=Double.POSITIVE_INFINITY; while((line=br.readLine())!=null){ String[] l=line.split("\t"); String type=l[1]; double score=Double.parseDouble(l[2]); if(discardZeroEntries&&score<=1E-5){ continue; } if(log)score=-Math.log(1-score); if(type.equals("TruePositiveMatch")) TPs.add(score,type,i); if(type.equals("FalsePositiveMatch")) FPs.add(score,type,i); minValue=Math.min(minValue, score); i++; } // if(log){ // for(int k=0;k<TPs.size();k++){ // TPs.sample.set(k,TPs.sample.get(k)-minValue); // } // for(int k=0;k<FPs.size();k++){ // FPs.sample.set(k,FPs.sample.get(k)-minValue); // } // } br.close(); return all; } public static List<List<Double>> getSimulatedScores(int[] n, List<RealDistribution> distributions){ List<List<Double>> sample_sep=new ArrayList<List<Double>>(); for(int i=0;i<n.length;i++){ RealDistribution nd=distributions.get(i); List<Double> sample_curr=new ArrayList<Double>(); for(double d:nd.sample(n[i])){ sample_curr.add(d); } sample_sep.add(sample_curr); } return sample_sep; } public static void writeData(File outputFile, List<Double> data, List<Type> types) throws Exception{ if(!outputFile.getParentFile().exists())outputFile.getParentFile().mkdirs(); BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); int i=0; for(Double d:data){ bw.write(Double.toString(d)); if(types!=null)bw.write("\t"+types.get(i++)); bw.newLine(); } bw.close(); } public static void writeDistribution(File outputFile, List<Double> data, List<InterfaceMLDistribution> distributions, List<Map<String, Double>> parameters) throws Exception{ if(!outputFile.getParentFile().exists())outputFile.getParentFile().mkdirs(); BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); double minValue=Double.POSITIVE_INFINITY; double maxValue=Double.NEGATIVE_INFINITY; for(double d:data){ minValue=Math.min(minValue, d); maxValue=Math.max(maxValue, d); } double step=(maxValue-minValue)/1000; for(double x=minValue;x<=maxValue;x+=step){ bw.write(Double.toString(x)); for(int i=0;i<distributions.size();i++){ InterfaceMLDistribution d=distributions.get(i); Map<String, Double> p=parameters.get(i); Double v=p.get("pi")*d.getDensity(x, p); bw.write("\t"+v); } bw.newLine(); } bw.close(); } public static void writeQValues(File outputFile, String description, List<Double> qValuesReal, List<Double> qValuesPred)throws Exception{ if(!outputFile.getParentFile().exists())outputFile.getParentFile().mkdirs(); BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); bw.write(description); bw.newLine(); bw.write("calculated qValue\testimated qValue"); bw.newLine(); double sum=0; int n=0; for(int i=0;i<qValuesReal.size();i++){ sum+=qValuesPred.get(i); n+=1; if(i==qValuesReal.size()-1||Double.compare(qValuesReal.get(i+1),qValuesReal.get(i))!=0){ bw.write(qValuesReal.get(i)+"\t"+sum/n); bw.newLine(); n=0; sum=0; } } bw.close(); } public static void writePValues(File outputFile, String description, List<Double> pValuesPred, int steps)throws Exception{ Locale.setDefault(Locale.US); DecimalFormat df=new DecimalFormat("0.000"); int[] freq=new int[steps]; int all=0; for(double d:pValuesPred){ freq[(int)Math.floor(d*steps)]++; all++; } if(!outputFile.getParentFile().exists())outputFile.getParentFile().mkdirs(); BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); bw.write(description); bw.newLine(); bw.write("estimated pValue\tFrequency"); bw.newLine(); for(int i=0;i<freq.length;i++){ bw.write(df.format(1.0*i/steps+0.5/steps)+"\t"+1.0*freq[i]/all); bw.newLine(); } bw.close(); } }
10,025
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
EM.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/EM.java
package de.unijena.bioinf.em; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import org.apache.commons.math3.distribution.ExponentialDistribution; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.distribution.GumbelDistribution; import org.apache.commons.math3.distribution.LogisticDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.RandomGenerator; public class EM { public final Sample sample; public List<InterfaceMLDistribution> distributions; int maxIterations=10000; double minChangeLikelihood=1E-20; public EM(Sample sample, List<InterfaceMLDistribution> distributions){ for(int i=0;i<distributions.size();i++)distributions.get(i).preprocessSample(sample.sample); this.sample=sample; this.distributions=distributions; } public EM(Sample sample, InterfaceMLDistribution distribution){ this(sample, Arrays.asList(new InterfaceMLDistribution[]{distribution})); } public EM(Sample sample, List<InterfaceMLDistribution> distributions, int maxIterations, double minChangeLikelihood){ this(sample, distributions); this.maxIterations=maxIterations; this.minChangeLikelihood=minChangeLikelihood; } public EM(Sample sample, InterfaceMLDistribution distribution, int maxIterations, double minChangeLikelihood){ this(sample, distribution); this.maxIterations=maxIterations; this.minChangeLikelihood=minChangeLikelihood; } public EMResult doEM(boolean verb) throws Exception{ List<List<Double>> expectations=EMUtils.initializeRandomExpectations(sample.sample.size(), distributions.size()); List<Map<String, Double>> parameters=null; int iteration=0; double likelihood=Double.NEGATIVE_INFINITY; double changeLikelihood=Double.POSITIVE_INFINITY; while(iteration++<maxIterations&&changeLikelihood>minChangeLikelihood){ List<Map<String, Double>> parameters_new=EMUtils.MStep(distributions, expectations); if(verb){ System.out.println("iteration "+iteration); for(Map<String, Double> p:parameters_new){ for(Entry<String, Double> e:p.entrySet()){ System.out.print(e.getKey()+": "+e.getValue()+"\t"); } System.out.println(); } } List<List<Double>> expectations_new=EMUtils.EStep(distributions, parameters_new); double currLikelihood=EMUtils.getLogLikelihood(distributions, parameters_new); changeLikelihood=currLikelihood-likelihood; if(verb){ System.out.println("LogLik "+currLikelihood); System.out.println("Delta LogLik "+changeLikelihood+"\n"); } if(changeLikelihood<0) System.out.println("delta likelihood decreased?!" ); likelihood=currLikelihood; expectations=expectations_new; parameters=parameters_new; } parameters=EMUtils.MStep(distributions, expectations); EMResult result=new EMResult(sample.sample, expectations, distributions, parameters, likelihood); return result; } private static void getStandardOutput(Process proc) throws IOException { BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); // read the output from the command System.out.println("Here is the standard output of the command:\n"); String s = null; while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command System.out.println("Here is the standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } } private boolean checkExpectations(List<List<Double>> expectations){ for(int i=0;i<expectations.get(0).size();i++){ double sum=0; for(int j=0;j<expectations.size();j++){ sum+=expectations.get(j).get(i); } if(Math.abs(1-sum)>1E-7)return false; } return true; } private boolean checkParameters(List<Map<String, Double>> parameters){ double sum=0; for(Map<String, Double> p:parameters){ sum+=p.get("pi"); } if(Math.abs(1-sum)>1E-7)return false; return true; } }
4,706
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MLNormalDistribution.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/MLNormalDistribution.java
package de.unijena.bioinf.em; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.distribution.NormalDistribution; public class MLNormalDistribution extends MLDistribution implements InterfaceMLDistribution { public MLNormalDistribution(boolean inverse, double shift) { super(inverse, shift); // TODO Auto-generated constructor stub } public String getDescription(){ return "NormalDistribution"+(inverse?"Inverse":""); } public Map<String, Double> MStep(List<Double> expectation){ Map<String, Double> parameters=new HashMap<String, Double>(); double pi=EMUtils.getPi(expectation); parameters.put("pi", pi); double mu=EMUtils.getMu(sample, expectation); parameters.put("mu",mu); double sd=EMUtils.getSD(sample, expectation, mu); parameters.put("sd", Math.max(1E-10,sd)); return parameters; } @Override public double getNumericalMean(Map<String, Double> parameters) throws Exception { return new NormalDistribution(parameters.get("mu"), parameters.get("sd")).getNumericalMean(); } @Override public double getDensityUnprocessed(double x, Map<String, Double> parameters) { return new NormalDistribution(parameters.get("mu"), parameters.get("sd")).density(x); } @Override public double getCumulativeProbabilityUnprocessed(double x1, Map<String, Double> parameters) { return new NormalDistribution(parameters.get("mu"), parameters.get("sd")).cumulativeProbability(x1); } }
1,560
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MLBetaDistribution.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/MLBetaDistribution.java
package de.unijena.bioinf.em; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.math3.distribution.BetaDistribution; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.special.Gamma; public class MLBetaDistribution extends MLDistribution implements InterfaceMLDistribution { public MLBetaDistribution(boolean inverse, double shift) { super(inverse, shift); // TODO Auto-generated constructor stub } public String getDescription(){ return "BetaDistribution"+(inverse?"Inverse":""); } public Map<String, Double> MStep(List<Double> expectation){ Map<String, Double> parameters=new HashMap<String, Double>(); double pi=EMUtils.getPi(expectation); parameters.put("pi", pi); double mu=EMUtils.getMu(sample, expectation); double sd=EMUtils.getSD(sample, expectation,mu); double alpha=Math.pow(mu,2)*(1-mu)/Math.pow(sd,2)-mu; double beta=Math.pow(1-mu,2)*mu/Math.pow(sd,2)-(1-mu); parameters.put("alpha", alpha); parameters.put("beta",beta); return parameters; } @Override public double getNumericalMean(Map<String, Double> parameters) throws Exception { return new BetaDistribution(parameters.get("alpha"), parameters.get("beta")).getNumericalMean(); } @Override public double getDensityUnprocessed(double x, Map<String, Double> parameters) throws Exception { return new BetaDistribution(parameters.get("alpha"), parameters.get("beta")).density(x); } @Override public double getCumulativeProbabilityUnprocessed(double x1, Map<String, Double> parameters) throws Exception { return new BetaDistribution(parameters.get("alpha"), parameters.get("beta")).cumulativeProbability(x1); } }
1,911
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MLExponentialDistribution.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/MLExponentialDistribution.java
package de.unijena.bioinf.em; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.math3.distribution.ExponentialDistribution; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.distribution.NormalDistribution; public class MLExponentialDistribution extends MLDistribution implements InterfaceMLDistribution { public MLExponentialDistribution(boolean inverse, double shift) { super(inverse, shift); // TODO Auto-generated constructor stub } public String getDescription(){ return "ExponentialDistribution"+(inverse?"Inverse":""); } public Map<String, Double> MStep(List<Double> expectation){ Map<String, Double> parameters=new HashMap<String, Double>(); double pi=EMUtils.getPi(expectation); parameters.put("pi", pi); double mu=EMUtils.getMu(sample, expectation); parameters.put("mu", mu); return parameters; } @Override public double getNumericalMean(Map<String, Double> parameters) throws Exception { return new ExponentialDistribution(parameters.get("mu")).getNumericalMean(); } @Override public double getDensityUnprocessed(double x, Map<String, Double> parameters) throws Exception { return new ExponentialDistribution(parameters.get("mu")).density(x); } @Override public double getCumulativeProbabilityUnprocessed(double x1, Map<String, Double> parameters) throws Exception { return new ExponentialDistribution(parameters.get("mu")).cumulativeProbability(x1); } }
1,619
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
Sample.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/em/Sample.java
package de.unijena.bioinf.em; import java.util.ArrayList; import java.util.List; public class Sample { public enum Type{FalsePositiveMatch, TruePositiveMatch, DecoyMatch} public List<Double> sample=new ArrayList<Double>(); public List<Type> types=new ArrayList<Type>(); public List<Integer> ranks=new ArrayList<Integer>(); public Sample(){ } public Sample(Sample s){ for(Double d:s.sample)this.sample.add(d); for(Type d:s.types)this.types.add(d); for(Integer d:s.ranks)this.ranks.add(d); } public Sample(List<Sample> sample){ for(Sample s:sample)this.add(s); } public Sample(List<Double> sample, List<Type> types, List<Integer> ranks){ this.sample=sample; this.types=types; this.ranks=ranks; } public void add(Double score, String type, Integer rank){ Type res=null; for(Type s:Type.values()){ if(s.toString().equals(type))res=s; } add(score, res, rank); } public void add(Double score, Type type, int rank){ sample.add(score); types.add(type); ranks.add(rank); } public void add(Sample s) { for(int i=0;i<s.size();i++){ add(s.sample.get(i), s.types.get(i), s.ranks.get(i)); } } public int size(){ return sample.size(); } public Sample sortByRank(){ Sample s=new Sample(this); for(int i=0;i<s.ranks.size()-1;i++){ int minValue=Integer.MAX_VALUE; int minIndex=Integer.MAX_VALUE; for(int j=i;j<s.ranks.size();j++){ if(s.ranks.get(j)<minValue){ minValue=s.ranks.get(j); minIndex=j; } } change(i,minIndex, s.sample); change(i,minIndex, s.types); change(i,minIndex, s.ranks); } return s; } public static void change(int i, int j, List list){ Object o=list.get(i); list.set(i,list.get(j)); list.set(j, o); } public List<Double> getFDRs(){ Sample s=sortByRank(); List<Double> fdrs=new ArrayList<Double>(); int numberFPs=0;; int numberTPs=0; for(int i=0;i<s.types.size();i++){ if(s.types.get(i).equals(Type.FalsePositiveMatch))numberFPs++; if(s.types.get(i).equals(Type.TruePositiveMatch))numberTPs++; fdrs.add(1d*numberFPs/(numberFPs+numberTPs)); } return fdrs; } public List<Double> getQValues(){ List<Double> fdrs=getFDRs(); for(int i=fdrs.size()-2;i>=0;i--){ fdrs.set(i,Math.min(fdrs.get(i+1), fdrs.get(i))); } return fdrs; } }
2,423
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
Main.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/treecomparison/Main.java
package de.unijena.bioinf.treecomparison; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.nio.file.Files; //generating tree alignments public class Main { static String queryLong="Agilent"; static String DBLong="Metlin"; public static void main(String[] args) throws Exception{ String queryShort=queryLong.substring(0,1); String DBShort=DBLong.substring(0,1); String[] withs=new String[]{ DBLong+"PositiveOriginal", DBLong+"PositiveReroot"}; String[] outs=new String[]{ queryShort+"POriginal-"+DBShort+"POriginal", queryShort+"POriginal-"+DBShort+"PReroot"}; String aligns=queryLong+"PositiveOriginal"; String dataset="D:\\metabo_tandem_ms\\MSBlast\\"; for(int i=0;i<withs.length;i++){ String align=dataset+"DB\\DataBases\\"+queryLong+"\\pos\\"+aligns+"\\dot\\"; String with=dataset+"DB\\DataBases\\"+DBLong+"\\pos\\"+withs[i]+"\\dot\\"; String output=dataset+"searchResults\\TreeAlignment\\pos\\"+outs[i]; File tmpAlignmentMatrix=new File(System.getProperty("java.io.tmpdir")+"\\tmp.csv"); System.out.println("starting... "); String s1="-z -x -j " + "-m "+tmpAlignmentMatrix.getAbsolutePath()+" " + "--align "+align+" " + "--with "+with; args=s1.split(" "); new de.unijena.bioinf.ftalign.Main().run(args); BufferedReader br=new BufferedReader(new FileReader(tmpAlignmentMatrix)); BufferedWriter bw=new BufferedWriter(new FileWriter(output+".csv")); bw.write("Query: "+align.replaceAll("dot","massbank")+";"); bw.newLine(); bw.write("DB: "+with.replaceAll("dot","massbank")+";"); bw.newLine(); bw.newLine(); String line; while((line=br.readLine())!=null){ bw.write(line.replaceAll("\"","").replaceAll("scores", "")); bw.newLine(); } br.close(); bw.close(); // System.out.println("starting... "); // s1="-z -f -x -j " + // "-m "+output+"FP.csv " + // "--align "+align+" " + // "--with "+with; // args=s1.split(" "); // new de.unijena.bioinf.ftalign.Main().run(args); // // System.out.println("...finished"); // File tmpDirQueryAndDB=new File(System.getProperty("java.io.tmpdir")+"\\QueryAndDB"); // if(tmpDirQueryAndDB.exists()){ // for (File f:tmpDirQueryAndDB.listFiles())f.delete(); // tmpDirQueryAndDB.delete(); // } // tmpDirQueryAndDB.mkdirs(); // for(File f:new File(align).listFiles()){ // if(f.getName().endsWith(".dot"))Files.copy(f.toPath(), new File(tmpDirQueryAndDB.getAbsolutePath()+"\\"+f.getName()).toPath()); // } // for(File f:new File(with).listFiles()){ // if(f.getName().endsWith(".dot"))Files.copy(f.toPath(), new File(tmpDirQueryAndDB.getAbsolutePath()+"\\"+f.getName()).toPath()); // } // // tmpAlignmentMatrix=new File(System.getProperty("java.io.tmpdir")+"\\tmp.csv"); // // System.out.println("starting... "); // s1="-z -f -x -j " + // "-m "+tmpAlignmentMatrix.getAbsolutePath()+" " + // "--align "+tmpDirQueryAndDB.getAbsolutePath()+" " + // "--with "+align; // args=s1.split(" "); // new de.unijena.bioinf.ftalign.Main().run(args); // // br=new BufferedReader(new FileReader(tmpAlignmentMatrix)); // bw=new BufferedWriter(new FileWriter(output+"FP.csv")); // // File[] left=new File(align).listFiles(); // File[] right=new File(with).listFiles(); // // double[][] scores=new double[left.length][right.length]; // String[] header=br.readLine().split(","); // int[] headerIndexes=new int[header.length]; // for(int j=0;j<header.length;j++)headerIndexes[j]=Integer.MIN_VALUE; // for(int j=0;j<header.length;j++){ // for(int k=0;k<left.length;k++){ // if(header[j].replaceAll("\"","").equals(left[k].getName().replaceAll(".dot",""))){ // headerIndexes[j]=k; // continue; // } // } // } // while((line=br.readLine())!=null){ // String[] l=line.split(","); // String row=l[0]; // int indexRight=Integer.MIN_VALUE; // for(int j=0;j<right.length;j++)if(row.replaceAll("\"","").equals(right[j].getName().replaceAll(".dot","")))indexRight=j; // for(int j=1;j<l.length;j++){ // int indexLeft=headerIndexes[j]; // if(indexLeft!=Integer.MIN_VALUE&&indexRight!=Integer.MIN_VALUE){ // scores[indexLeft][indexRight]=Double.parseDouble(l[j]); // } // } // } // // bw.write("Query: "+align.replaceAll("dot","massbank")+";"); // bw.newLine(); // bw.write("DB: "+with.replaceAll("dot","massbank")+";"); // bw.newLine(); // bw.newLine(); // // for(File h:right)bw.write(","+h.getName().replaceAll(".dot", "")); // bw.newLine(); // for(int k=0;k<scores.length;k++){ // bw.write(left[k].getName().replaceAll(".dot", "")); // for(double s:scores[k])bw.write(","+s); // bw.newLine(); // } // bw.close(); // br.close(); System.out.println("...finished"); // tmpDirQueryAndDB.delete(); } } }
5,153
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ResultList.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/ResultList.java
package de.unijena.bioinf.statistics; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.deocy.Utils; public class ResultList{ Query query; List<Result> results; public ResultList(){ this.results=new ArrayList<Result>(); } public ResultList(ResultList rl){ this.query=rl.query; this.results=new ArrayList<Result>(); this.results.addAll(rl.results); } public static List<ResultList> getMergedResults(File[] files, Map<String, MassBank> dbFiles) throws Exception{ List<ResultList>[] tmp= new ArrayList[files.length]; int i=0; for(File f:files){ tmp[i++]=getResults(f, dbFiles); } List<ResultList> results=ResultList.mergeResults(tmp); return results; } public static List<ResultList> getResults(File f, Map<String, MassBank> dbFiles) throws Exception{ if (f.getName().endsWith(".txt")){ return getResultsTXT(f, dbFiles); }else{ return getResultsCSV(f, dbFiles); } } public static List<ResultList> getResultsCSV(File f, Map<String, MassBank> dbFiles) throws Exception{ List<ResultList> results=new ArrayList<ResultList>(); BufferedReader br=new BufferedReader(new FileReader(f)); br.readLine();br.readLine();br.readLine(); String line=br.readLine(); List<String> resultIDs=Arrays.asList(line.split(",",Integer.MAX_VALUE)); List<MassBank> resultIDsMassBank=new ArrayList<MassBank>(); for(String s:resultIDs)resultIDsMassBank.add(dbFiles.get(s)); ResultList rl=null; while((line=br.readLine())!=null){ String l[]=line.split(","); rl=new ResultList(); results.add(rl); Query q=new Query(l[0]); q.massbank=dbFiles.get(q.queryID); rl.query=q; for(int i=1;i<l.length;i++){ String[] res=l[i].split(" "); double score=Double.parseDouble(res[0]); if(score>0){ Result r=new Result(resultIDs.get(i),Integer.parseInt(res[1]), score); r.massbank=resultIDsMassBank.get(i); rl.results.add(r); r.isTrueMatch=rl.query.massbank.inchi.equals(r.massbank.inchi); } } Collections.sort(rl.results); } br.close(); return results; } public static List<ResultList> getResultsTXT(File f, Map<String, MassBank> dbFiles) throws Exception{ List<ResultList> results=new ArrayList<ResultList>(); BufferedReader br=new BufferedReader(new FileReader(f)); String line; ResultList rl=null; while((line=br.readLine())!=null){ if(line.startsWith("query")){ rl=new ResultList(); results.add(rl); Query q=new Query(line.split("\t")[1]); q.massbank=dbFiles.get(q.queryID); rl.query=q; }else if(line.startsWith("result")){ Result r=new Result(line.split("\t")); r.massbank=dbFiles.get(r.resultID); rl.results.add(r); r.isTrueMatch=rl.query.massbank.inchi.equals(r.massbank.inchi); } } br.close(); return results; } public static List<ResultList> mergeResults(List<ResultList>[] resultLists) throws Exception{ List<ResultList> result=new ArrayList<ResultList>(); for(List<ResultList> resultList:resultLists){ for(ResultList rl_tmp_1:resultList){ ResultList found=null; for(ResultList rl_tmp_2:result){ if(rl_tmp_1.query.queryID.equals(rl_tmp_2.query.queryID)){ found=rl_tmp_2; break; } } if(found!=null){ found.results.addAll(rl_tmp_1.results); }else{ result.add(new ResultList(rl_tmp_1)); } } } for(ResultList resultList:result){ Collections.sort(resultList.results); } return result; } public void filterResultsByMass(boolean onlySame, double ppm, double ae){ Iterator<Result> it=results.iterator(); double mass=query.massbank.mf.getMass(); double error=Utils.getAbsoluteErrorForMass(mass, ppm, ae); while(it.hasNext()){ Result r=it.next(); boolean isNotSame=Math.abs(r.massbank.mf.getMass()-mass)>error; if((onlySame&&isNotSame)||(!onlySame&&!isNotSame))it.remove(); } } public void filterResultsByInChi(boolean retainSame){ String inchiQuery=query.massbank.inchi; Iterator<Result> it=results.iterator(); while(it.hasNext()){ Result r=it.next(); String inchiResult=r.massbank.inchi; boolean isNotSame=inchiQuery==null||inchiResult==null||inchiQuery.isEmpty()||inchiResult.isEmpty()||!inchiQuery.equals(inchiResult); if((retainSame&&isNotSame)||(!retainSame&&!isNotSame))it.remove(); } } }
4,722
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
HitStatistic.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/HitStatistic.java
package de.unijena.bioinf.statistics; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.statistics.SimilarityMatrix.DatabaseType; import de.unijena.bioinf.statistics.SimilarityMatrix.MatchType; public class HitStatistic { enum HitDescription{BestWorst, Best, NotFirstMatch, NotInDB, NotInQuery} enum MatchType{TruePositiveMatch, FalsePositiveMatch, DecoyMatch}; enum HitMerge{Add, Merge}; SimilarityMatrix m=null; Double averageRankMin=null; Double averageRankMedium=null; Double averageRankMax=null; Integer numberTopHitsMin=null; Integer numberTopHitsMax=null; Double numberTopHitsMedium=null; Integer numberPossibleHits=null; Integer numberSearches=null; Integer numberEntriesWithAtLeastOneHit=null; Double AUCMax=null; Double AUCAverage=null; Double AUCAverageSmall=null; Double AUCMin=null; Double F1ScoreMin=null; Double F1ScoreMax=null; List<Hit> hits=new ArrayList<Hit>(); static final String sep=System.getProperty("file.separator"); public HitStatistic(){} public HitStatistic(File inputFile, TreeMap<String, MassBank> massbankFilesOriginal) throws Exception{ BufferedReader br=new BufferedReader(new FileReader(inputFile)); String line=br.readLine(); List<String> header=Arrays.asList(line.split("\t",Integer.MAX_VALUE)); while((line=br.readLine())!=null){ Hit h=new Hit(); hits.add(h); String l[]=line.split("\t",Integer.MAX_VALUE); h.massbankQuery=massbankFilesOriginal.get(SimilarityMatrix.getIDDatasetChargeOrigin(l[header.indexOf("massbankID query")])); h.numberEntries=Integer.parseInt(l[header.indexOf("number entries")]); if(!l[header.indexOf("massbankIDs hits")].isEmpty()){ for(String s:l[header.indexOf("massbankIDs hits")].split(";")) h.hitsInDB.add(massbankFilesOriginal.get(SimilarityMatrix.getIDDatasetChargeOrigin(s))); } if(!h.hitsInDB.isEmpty()){ h.scoreBestHit=Double.parseDouble(l[header.indexOf("score best hit")]); h.minRankBestHit=Integer.parseInt(l[header.indexOf("min rank best hit")]); h.maxRankBestHit=Integer.parseInt(l[header.indexOf("max rank best hit")]); } if(!l[header.indexOf("massbankIDs non hits")].isEmpty()){ for(String s:l[header.indexOf("massbankIDs non hits")].split(";")) h.bestNonHits.add(massbankFilesOriginal.get(SimilarityMatrix.getIDDatasetChargeOrigin(s))); } if(!h.bestNonHits.isEmpty()){ h.scoreBestNonHit=Double.parseDouble(l[header.indexOf("score best non hit")]); } } br.close(); } public static String getHitDescriptionString(HitDescription hd){ switch (hd){ case BestWorst: return "best case worst case"; case Best: return "best case"; case NotFirstMatch: return "not first match"; case NotInDB: return "not in DB"; case NotInQuery: return "not in query"; default: return ""; } } public static int getHitDescriptionRank(HitDescription hd){ switch (hd){ case BestWorst: return 3; case Best: return 2; case NotFirstMatch: return 1; case NotInDB: return 0; case NotInQuery: return 0; default: return -1; } } public static Integer compareHitDescription(HitDescription hd1, HitDescription hd2){ int rank1=getHitDescriptionRank(hd1); int rank2=getHitDescriptionRank(hd2); if(rank1==0||rank2==0)return null; return Integer.compare(rank1,rank2); } public double getAverageRankMin(){ if(averageRankMin!=null)return averageRankMin; double sum=0; int k=0; for(Hit h:hits){ if(h.isEmpty()||h.noCorrectHit())continue; sum+=h.minRankBestHit; k++; } averageRankMin=sum/k; return averageRankMin; } public double getAverageRankMax(){ if(averageRankMax!=null)return averageRankMax; double sum=0; int k=0; for(Hit h:hits){ if(h.isEmpty()||h.noCorrectHit())continue; sum+=h.maxRankBestHit; k++; } averageRankMax=sum/k; return averageRankMax; } public double getAverageRankMedium(){ if(averageRankMedium!=null)return averageRankMedium; double sum=0; int k=0; for(Hit h:hits){ if(h.isEmpty()||h.noCorrectHit())continue; sum+=h.getMediumRankBestHit(); k++; } averageRankMedium=sum/k; return averageRankMedium; } public double getNumberTopHitsMax(){ if(numberTopHitsMax!=null)return numberTopHitsMax; int k=0; for(Hit h:hits){ if(h.isEmpty()||h.noCorrectHit())continue; if(h.correctHitMinRank())k++; } numberTopHitsMax=k; return numberTopHitsMax; } public double getNumberTopHitsMin(){ if(numberTopHitsMin!=null)return numberTopHitsMin; int k=0; for(Hit h:hits){ if(h.isEmpty()||h.noCorrectHit())continue; if(h.correctHitMaxRank())k++; } numberTopHitsMin=k; return numberTopHitsMin; } public double getNumberTopHitsMedium(){ if(numberTopHitsMedium!=null)return numberTopHitsMedium; double k=0; for(Hit h:hits){ if(h.isEmpty()||h.noCorrectHit()||!h.correctHitMinRank())continue; k+=h.correctHitMediumRank(); } numberTopHitsMedium=k; return numberTopHitsMedium; } public int getNumberPossibleHits(){ if(numberPossibleHits!=null)return numberPossibleHits; int k=0; for(Hit h:hits){ if(h.isEmpty())continue; if(!h.noCorrectHit())k++; } numberPossibleHits=k; return numberPossibleHits; } public int getNumberEntriesWithAtLeastOneHit(){ if(numberEntriesWithAtLeastOneHit!=null)return numberEntriesWithAtLeastOneHit; int k=0; for(Hit h:hits){ if(h.bestNonHits.isEmpty()&&h.noCorrectHit())continue; k++; } numberEntriesWithAtLeastOneHit=k; return numberEntriesWithAtLeastOneHit; } public int getNumberSearches(){ if(numberSearches!=null)return numberSearches; numberSearches=hits.size(); return numberSearches; } public String toString(){ String result=""; result+="ranks:\t"+getAverageRankMin()+"\t"+getAverageRankMedium()+"\t"+getAverageRankMax()+"\n"; result+="top hits:\t"+getNumberTopHitsMin()+"\t"+getNumberTopHitsMax()+"\n"; result+="possible hits:\t"+getNumberPossibleHits()+"\n"; result+="searches:\t"+getNumberSearches()+"\n"; return result; } public static String getHeaderString(){ return "number searches\tpossible hits\tnumber top hits min\tnumber top hits medium\tnumber top hits max\taverage rank min\taverage rank medium\taverage rank max\tAUC min\tAUC average\tAUC max\tAUC average 0.1\tF1 min\tF1 max"; } public String toEntryString(){ String result=""; result+=getNumberSearches()+"\t"; result+=getNumberPossibleHits()+"\t"; result+=getNumberTopHitsMin()+"\t"+getNumberTopHitsMedium()+"\t"+getNumberTopHitsMax()+"\t"; result+=getAverageRankMin()+"\t"+getAverageRankMedium()+"\t"+getAverageRankMax()+"\t"; result+=getAUCMin()+"\t"+getAUCAverage()+"\t"+getAUCMax()+"\t"; result+=getAUCAverageSmall()+"\t"; result+=getF1ScoreMin()+"\t"+getF1ScoreMax(); return result; } public double getAUCMax(){ if(AUCMax!=null)return AUCMax; List<Hit> hits=new ArrayList<Hit>(); for(Hit h:this.hits)if(!h.isEmpty())hits.add(h); Collections.sort(hits,new HitComparator(HitComparator.SortAtEqualScore.BESTCASE)); AUCMax=getAUC(hits); return AUCMax; } public double getAUCAverage(){ if(AUCAverage!=null)return AUCAverage; AUCAverage=getAUCAverageAll(Double.POSITIVE_INFINITY); return AUCAverage; } public double getAUCAverageSmall(){ if(AUCAverageSmall!=null)return AUCAverageSmall; AUCAverageSmall=getAUCAverageAll(0.1); return AUCAverageSmall; } public double getAUCAverageAll(double fpr){ List<Hit> hits=new ArrayList<Hit>(); for(Hit h:this.hits)if(!h.isEmpty())hits.add(h); Collections.sort(hits,new HitComparator(HitComparator.SortAtEqualScore.BESTCASE)); return getAUCAverage(hits,fpr); } public List<double[]> getROCMax(){ List<Hit> hits=new ArrayList<Hit>(); for(Hit h:this.hits)if(!h.isEmpty())hits.add(h); Collections.sort(hits,new HitComparator(HitComparator.SortAtEqualScore.BESTCASE)); return getROC(hits); } public List<double[]> getROCAverage(){ List<Hit> hits=new ArrayList<Hit>(); for(Hit h:this.hits)if(!h.isEmpty())hits.add(h); Collections.sort(hits,new HitComparator(HitComparator.SortAtEqualScore.BESTCASE)); return getROCAverage(hits); } public double getAUCMin(){ if(AUCMin!=null)return AUCMin; List<Hit> hits=new ArrayList<Hit>(); for(Hit h:this.hits)if(!h.isEmpty())hits.add(h); Collections.sort(hits,new HitComparator(HitComparator.SortAtEqualScore.WORSTCASE)); AUCMin=getAUC(hits); return AUCMin; } public double getF1ScoreMin(){ if(F1ScoreMin!=null)return F1ScoreMin; List<Hit> hits=new ArrayList<Hit>(); for(Hit h:this.hits)if(!h.isEmpty())hits.add(h); Collections.sort(hits,new HitComparator(HitComparator.SortAtEqualScore.WORSTCASE)); F1ScoreMin=getF1Score(hits); return F1ScoreMin; } public double getF1ScoreMax(){ if(F1ScoreMax!=null)return F1ScoreMax; List<Hit> hits=new ArrayList<Hit>(); for(Hit h:this.hits)if(!h.isEmpty())hits.add(h); Collections.sort(hits,new HitComparator(HitComparator.SortAtEqualScore.BESTCASE)); F1ScoreMax=getF1Score(hits); return F1ScoreMax; } public double getF1Score(List<Hit> hits){ int allPositives=0; for(Hit h:hits){ if(h.correctHitMinRank())allPositives++; } int currentNumberTruePositives=0; int currentNumberFalsePositives=0; double F=0; int countF=0; for(Hit h:hits){ if(h.correctHitMinRank())currentNumberTruePositives++; else currentNumberFalsePositives++; double sensitivity=1.0*currentNumberTruePositives/allPositives; double precision=1.0*currentNumberTruePositives/(currentNumberTruePositives+currentNumberFalsePositives); if(precision==0&&sensitivity==0){ F+=0; }else{ F+=2*precision*sensitivity/(precision+sensitivity); } countF++; } return F/countF; } private double getAUC(List<Hit> hits) { List<Integer> numbers=new ArrayList<Integer>(); numbers.add(0); for(Hit h:hits){ if(h.correctHitMinRank())numbers.add(numbers.get(numbers.size()-1)+1); else numbers.add(numbers.get(numbers.size()-1)); } double result=0; int correctHits=0; int inCorrectHits=0; for(int i=1;i<numbers.size();i++){ if(numbers.get(i-1)==numbers.get(i)){ result+=numbers.get(i-1); inCorrectHits++; }else{ correctHits++; } } result/=(inCorrectHits*correctHits); return result; } private double getAUCAverage(List<Hit> hits, double fpr) { List<double[]> numbers=getROCAverage(hits); double result=0; double maxX=numbers.get(numbers.size()-1)[0]; double maxY=numbers.get(numbers.size()-1)[1]; for(int i=1;i<numbers.size();i++){ if(numbers.get(i)[0]/maxX<fpr){ double deltaX=numbers.get(i)[0]-numbers.get(i-1)[0]; double deltaY=numbers.get(i)[1]-numbers.get(i-1)[1]; result+=deltaX*deltaY/2+numbers.get(i-1)[1]*deltaX; }else{ double deltaX=fpr*maxX-numbers.get(i-1)[0]; double deltaY=numbers.get(i)[1]-numbers.get(i-1)[1]; result+=deltaX*deltaY/2+numbers.get(i-1)[1]*deltaX; break; } } result/=(maxX*maxY); return result; } private List<double[]> getROCAverage(List<Hit> hits) { List<List<Hit>> hitsTmp=new ArrayList<List<Hit>>(); List<Hit> hTmp=new ArrayList<Hit>(); for(int i=0;i<hits.size();i++){ if(i==0||hits.get(i).getBestScore()!=hits.get(i-1).getBestScore()){ hTmp=new ArrayList<Hit>(); hitsTmp.add(hTmp); } hTmp.add(hits.get(i)); } List<double[]> numbers=new ArrayList<double[]>(); numbers.add(new double[]{0.0,0.0}); double numberCorrectHits=0; double numberWrongHits=0; for(List<Hit> hitList:hitsTmp){ for(Hit h:hitList){ double correctHits=0; if(h.correctHitMinRank())correctHits=h.correctHitMediumRank(); numberCorrectHits+=correctHits; numberWrongHits+=1-correctHits; } numbers.add(new double[]{numberWrongHits, numberCorrectHits}); } double maxX=numbers.get(numbers.size()-1)[0]; double maxY=numbers.get(numbers.size()-1)[1]; for(int i=0;i<numbers.size();i++){ numbers.get(i)[0]=numbers.get(i)[0]/maxX; numbers.get(i)[1]=numbers.get(i)[1]/maxY; } return numbers; } private List<double[]> getROC(List<Hit> hits) { List<double[]> result=new ArrayList<double[]>(); int an=0; int ap=0; for(Hit h:hits){ if(h.correctHitMinRank())ap++; else an++; } int fp=0; int rp=0; result.add(new double[]{0.0,0.0}); for(Hit h:hits){ if(h.correctHitMinRank())rp++; else fp++; result.add(new double[]{1.0*fp/(an),1.0*rp/(ap)}); } return result; } public void writeHitStatisticToFile(File outputFile) throws Exception{ Map<MassBank, HitDescription> result=getHitDescription(); Map<MassBank, Hit> massbank2Hit=new HashMap<MassBank, Hit>(); for(Hit h:hits){ massbank2Hit.put(h.massbankQuery, h); } BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); bw.write("massbankID query\tnumber entries\tmassbankIDs hits\tscore best hit\tmin rank best hit\tmax rank best hit\tmassbankIDs non hits\tscore best non hit\t hit description"); bw.newLine(); for(Entry<MassBank, HitDescription> e:result.entrySet()){ Hit h=massbank2Hit.get(e.getKey()); String mbHits=""; for(int i=0;i<h.hitsInDB.size();i++){ if(i!=0)mbHits+=";"; mbHits+=h.hitsInDB.get(i).massbankID; } String mbNonHits=""; for(int i=0;i<h.bestNonHits.size();i++){ if(i!=0)mbNonHits+=";"; mbNonHits+=h.bestNonHits.get(i).massbankID; } bw.write( h.massbankQuery.massbankID+"\t"+ h.numberEntries+"\t"+ mbHits+"\t"+ h.scoreBestHit+"\t"+ h.minRankBestHit+"\t"+ h.maxRankBestHit+"\t"+ mbNonHits+"\t"+ h.scoreBestNonHit+"\t"+ getHitDescriptionString(e.getValue())); bw.newLine(); } bw.close(); } public Map<MassBank, HitDescription> getHitDescription() throws Exception{ Map<MassBank, HitDescription> result=new TreeMap<MassBank, HitDescription>(); for(Hit h:hits){ HitDescription description=null; if(h.noCorrectHit())description=HitDescription.NotInDB; else{ if(h.correctHitMinRank())description=HitDescription.Best; else description=HitDescription.NotFirstMatch; if(h.correctHitMaxRank()) description=HitDescription.BestWorst; } result.put(h.massbankQuery,description); } return result; } public static void writeROCCurves(File outputFile, TreeMap<String, HitStatistic> hits) throws Exception{ XYSeriesCollection dataset = new XYSeriesCollection(); for(Entry<String, HitStatistic> e:hits.entrySet()){ File txtFile=new File(outputFile.getAbsolutePath().replaceAll(".jpg","_"+e.getKey().split("-")[2]+".txt")); BufferedWriter bw=new BufferedWriter(new FileWriter(txtFile)); XYSeries series= new XYSeries(e.getKey()); bw.write("false positive rate\tsensitivity"); bw.newLine(); List<double[]> roc=e.getValue().getROCAverage(); for(double[] r:roc){ bw.write(r[0]+"\t"+r[1]); bw.newLine(); series.add(r[0],r[1]); } dataset.addSeries(series); bw.close(); } final JFreeChart chart =ChartFactory.createXYLineChart("ROCCurve", "false positive rate", "sensitivity", dataset); ChartUtilities.saveChartAsJPEG(outputFile, chart, 1000, 400); } public void writeScoreDistributionOfTopRank(File outputFile, double step, String add) throws Exception{ File jpg=new File(outputFile.getPath()+sep+add+"ScoreDistributionTopRank"+"_"+m.getMethodsQueryAndDBString()+".jpg"); File txt=new File(outputFile.getPath()+sep+add+"ScoreDistributionTopRank"+"_"+m.getMethodsQueryAndDBString()+".txt"); Map<Double, Integer> topScoringMatchesAll=new TreeMap<Double,Integer>(); Map<Double, Integer> topScoringMatchesTrue=new TreeMap<Double,Integer>(); Map<Double, Integer> topScoringMatchesFalse=new TreeMap<Double,Integer>(); int numberTrueMatches=0; int numberFalseMatches=0; double maxValue=Double.NEGATIVE_INFINITY; for(Hit h:hits){ if(h.isEmpty())continue; Double valueOrig=h.getBestScore(); maxValue=Math.max(Math.round(valueOrig/step)*step,maxValue); } for(Hit h:hits){ if(h.isEmpty())continue; Double valueOrig=h.getBestScore(); valueOrig/=maxValue; double value=Math.round(valueOrig/step)*step; if(!topScoringMatchesAll.containsKey(value))topScoringMatchesAll.put(value, 0); topScoringMatchesAll.put(value,topScoringMatchesAll.get(value)+1); if(h.correctHitMinRank()){ if(!topScoringMatchesTrue.containsKey(value))topScoringMatchesTrue.put(value, 0); topScoringMatchesTrue.put(value,topScoringMatchesTrue.get(value)+1); numberTrueMatches++; }else{ if(!topScoringMatchesFalse.containsKey(value))topScoringMatchesFalse.put(value, 0); topScoringMatchesFalse.put(value,topScoringMatchesFalse.get(value)+1); numberFalseMatches++; } } BufferedWriter bw=new BufferedWriter(new FileWriter(txt)); Set<Double> v=new TreeSet<Double>(); bw.write("\t"+m.getMethodsQueryAndDBString()+"-true\t"+m.getMethodsQueryAndDBString()+"-wrong"); bw.newLine(); v.addAll(topScoringMatchesTrue.keySet()); v.addAll(topScoringMatchesFalse.keySet()); for(Double d:v){ bw.write(d+"\t"); Integer t=topScoringMatchesTrue.get(d); Integer f=topScoringMatchesFalse.get(d); bw.write((t!=null?1.0*t/numberTrueMatches:"")+"\t"); bw.write(""+(f!=null?1.0*f/numberFalseMatches:"")); bw.newLine(); } bw.close(); XYSeries seriesTrue = new XYSeries("True Hits ("+numberTrueMatches+")"); for(Entry<Double,Integer> m:topScoringMatchesTrue.entrySet()){ seriesTrue.add(m.getKey(),new Double(1.0*m.getValue()/numberTrueMatches)); } XYSeries seriesFalse = new XYSeries("False Hits ("+numberFalseMatches+")"); for(Entry<Double,Integer> m:topScoringMatchesFalse.entrySet()){ seriesFalse.add(m.getKey(),new Double(1.0*m.getValue()/numberFalseMatches)); } XYSeries seriesAll= new XYSeries("All Hits ("+(numberTrueMatches+numberFalseMatches)+")"); for(Entry<Double,Integer> m:topScoringMatchesAll.entrySet()){ seriesAll.add(m.getKey(),new Double(1.0*m.getValue()/(numberTrueMatches+numberFalseMatches))); } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(seriesTrue); dataset.addSeries(seriesFalse); dataset.addSeries(seriesAll); final JFreeChart chart =ChartFactory.createXYLineChart("Score Distribution", "score", "percentage", dataset); ChartUtilities.saveChartAsJPEG(jpg, chart, 1000, 400); } public static List<Hit> mergeHits(HitStatistic hsOriginal, HitStatistic hsDecoy, HitMerge hm){ for(Hit h:hsOriginal.hits)h.db=Hit.DataBase.Original; for(Hit h:hsDecoy.hits)h.db=Hit.DataBase.Decoy; List<Hit> tmp=new ArrayList<Hit>(); for(Hit h:hsOriginal.hits)if(!h.isEmpty()){ tmp.add(h); } System.out.println(); for(Hit h:hsDecoy.hits)if(!h.isEmpty()){ tmp.add(h); } List<Hit> mergedHits=new ArrayList<Hit>(); if(hm.equals(HitMerge.Add)){ mergedHits=tmp; }else if(hm.equals(HitMerge.Merge)){ Map<MassBank, Hit> mb=new HashMap<MassBank, Hit>(); for(Hit h:tmp){ if(!mb.containsKey(h.massbankQuery))mb.put(h.massbankQuery,h); else{ Hit h2=mb.get(h.massbankQuery); if(h.getBestScore()>h2.getBestScore()||(h.getBestScore()==h2.getBestScore()&&h.db.equals(Hit.DataBase.Original))){ mb.put(h.massbankQuery,h); } } } mergedHits.addAll(mb.values()); } return mergedHits; } public static void writeEstimatedQValueVSCalculatedQValueToFile(File outputFile,File outputFileMean, File outputFileHitlist, HitStatistic hsOriginal, HitStatistic hsDecoy, HitMerge hm, boolean FDR, List<MassBank> compoundsOfInterest) throws IOException{ for(Hit h:hsOriginal.hits)h.db=Hit.DataBase.Original; for(Hit h:hsDecoy.hits)h.db=Hit.DataBase.Decoy; List<Hit> mergedHits=mergeHits(hsOriginal, hsDecoy, hm); Collections.sort(mergedHits,new HitComparator(HitComparator.SortAtEqualScore.BESTCASE)); List<Double> bestScores=new ArrayList<Double>(); List<MatchType> matches=new ArrayList<MatchType>(); BufferedWriter bwHitlist=new BufferedWriter(new FileWriter(outputFileHitlist)); if(compoundsOfInterest!=null){ for(int i=0;i<compoundsOfInterest.size();i++){ if(i!=0)bwHitlist.write(";"); bwHitlist.write(compoundsOfInterest.get(i).massbankID); } bwHitlist.newLine(); } bwHitlist.write("massbank\tmatch type\tscore"); bwHitlist.newLine(); List<Double> FDRByDecoy=new ArrayList<Double>(); List<Double> FDRCalculated=new ArrayList<Double>(); int allTrueMatches=0; int allFalseMatches=0; for(Hit h:mergedHits){ if(compoundsOfInterest!=null&&!compoundsOfInterest.contains(h.massbankQuery))continue; if(h.isEmpty())continue; bestScores.add(h.getBestScore()); MatchType mt; if(h.db.equals(Hit.DataBase.Decoy))mt=MatchType.DecoyMatch; else if(h.correctHitMinRank()){ mt=MatchType.TruePositiveMatch; allTrueMatches++; }else{ mt=MatchType.FalsePositiveMatch; allFalseMatches++; } matches.add(mt); bwHitlist.write(h.massbankQuery.massbankID+"\t"+mt+"\t"+h.getBestScore()); bwHitlist.newLine(); } bwHitlist.close(); int countTrueMatches=0; int countFalseMatches=0; int countDecoyMatches=0; for(int i=0;i<matches.size();i++){ if(matches.get(i)==MatchType.DecoyMatch){ countDecoyMatches++; }else{ if(matches.get(i)==MatchType.TruePositiveMatch){ countTrueMatches++; }else{ countFalseMatches++; } double fdrDecoy=hm.equals(HitMerge.Merge)? 2.0*countDecoyMatches/(countDecoyMatches+countTrueMatches+countFalseMatches): 1.0*countDecoyMatches/(countTrueMatches+countFalseMatches)*allFalseMatches/(allFalseMatches+allTrueMatches); FDRByDecoy.add(fdrDecoy); FDRCalculated.add(1.0*countFalseMatches/(countFalseMatches+countTrueMatches)); } } double fdrDecoy= hm.equals(HitMerge.Merge)? 2.0*countDecoyMatches/(countDecoyMatches+countTrueMatches+countFalseMatches): 1.0*countDecoyMatches/(countTrueMatches+countFalseMatches)*allFalseMatches/(allFalseMatches+allTrueMatches); FDRByDecoy.add(fdrDecoy); FDRCalculated.add(1.0*countFalseMatches/(countFalseMatches+countTrueMatches)); if(!FDR){ double min=Double.POSITIVE_INFINITY; for(int i=FDRByDecoy.size()-1;i>=0;i--){ min=Math.min(FDRByDecoy.get(i),min); FDRByDecoy.set(i, min); } min=Double.POSITIVE_INFINITY; for(int i=FDRCalculated.size()-1;i>=0;i--){ min=Math.min(FDRCalculated.get(i),min); FDRCalculated.set(i, min); } } BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); BufferedWriter bwMean=new BufferedWriter(new FileWriter(outputFileMean)); if(compoundsOfInterest!=null){ for(int i=0;i<compoundsOfInterest.size();i++){ if(i!=0){ bw.write(";"); bwMean.write(";"); } bw.write(compoundsOfInterest.get(i).massbankID); bwMean.write(compoundsOfInterest.get(i).massbankID); } bw.newLine(); bwMean.newLine(); } bw.write("calculated qValue\testimated qValue"); bwMean.write("calculated qValue\testimated qValue"); bw.newLine(); bwMean.newLine(); for(int i=0;i<FDRCalculated.size();i++){ bw.write(FDRCalculated.get(i)+"\t"+FDRByDecoy.get(i)); bw.newLine(); } bw.close(); Map<Double, List<Double>> means=new TreeMap<Double, List<Double>>(); for(int i=0;i<FDRCalculated.size();i++){ if(!means.containsKey(FDRCalculated.get(i)))means.put(FDRCalculated.get(i), new ArrayList<Double>()); means.get(FDRCalculated.get(i)).add(FDRByDecoy.get(i)); } for(Entry<Double, List<Double>> e: means.entrySet()){ double m=0; for(double d:e.getValue())m+=d; m/=e.getValue().size(); bwMean.write(e.getKey()+"\t"+m); bwMean.newLine(); } bwMean.close(); } public static void writeQValuesDecoyHits(File decoyFolder, File outputFile, HitStatistic hsOriginal, List<MassBank> compoundsOfInterest, boolean FDR) throws Exception{ if(!decoyFolder.exists())decoyFolder.mkdir(); List<Hit> currentHits=new ArrayList<Hit>(); for(Hit h:hsOriginal.hits) if((compoundsOfInterest==null||compoundsOfInterest.contains(h.massbankQuery))&&!h.isEmpty()){ h.db=Hit.DataBase.Original; currentHits.add(h); } Collections.sort(currentHits,new HitComparator(HitComparator.SortAtEqualScore.BESTCASE)); List<MatchType> matches=new ArrayList<MatchType>(); List<Double> FDRCalculated=new ArrayList<Double>(); int allTrueMatches=0; int allFalseMatches=0; for(Hit h:currentHits){ if(compoundsOfInterest!=null&&!compoundsOfInterest.contains(h.massbankQuery))continue; if(h.isEmpty())continue; MatchType mt; if(h.db.equals(Hit.DataBase.Decoy))mt=MatchType.DecoyMatch; else if(h.correctHitMinRank()){ mt=MatchType.TruePositiveMatch; allTrueMatches++; }else{ mt=MatchType.FalsePositiveMatch; allFalseMatches++; } matches.add(mt); } int countTrueMatches=0; int countFalseMatches=0; for(int i=0;i<matches.size();i++){ if(matches.get(i)==MatchType.TruePositiveMatch){ countTrueMatches++; }else{ countFalseMatches++; } FDRCalculated.add(1.0*countFalseMatches/(countFalseMatches+countTrueMatches)); } FDRCalculated.add(1.0*countFalseMatches/(countFalseMatches+countTrueMatches)); if(!FDR){ double min=Double.POSITIVE_INFINITY; for(int i=FDRCalculated.size()-1;i>=0;i--){ min=Math.min(FDRCalculated.get(i),min); FDRCalculated.set(i, min); } } int n=currentHits.size(); File randomDecoyFile=new File(decoyFolder.getAbsolutePath()+sep+"RandomDecoyValues_"+n+".txt"); if(!randomDecoyFile.exists()){ createRandomDecoyQValues(n,randomDecoyFile); } List<double[]> avg=getAverageAndStandardDeviation(randomDecoyFile); BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); bw.write("calculated qValue\testimated qValue"); bw.newLine(); for(int i=0;i<Math.max(avg.size(), FDRCalculated.size());i++){ double v1=i>=FDRCalculated.size()?1:FDRCalculated.get(i); double v2=i>=avg.size()?1:avg.get(i)[0]; bw.write(v1+"\t"+calculateEstimatedQVAlue(v2,allFalseMatches,allTrueMatches)); bw.newLine(); } bw.close(); } private static double calculateEstimatedQVAlue(double value, int allFalseMatches, int allTrueMatches){ return value*allFalseMatches/(allFalseMatches+allTrueMatches); } public static List<double[]> getAverageAndStandardDeviation(File randomDecoyFile) throws IOException{ List<double[]> result=new ArrayList<double[]>(); BufferedReader br=new BufferedReader(new FileReader(randomDecoyFile)); List<String> header=Arrays.asList(br.readLine().split("\t")); List<Double> qValues=new ArrayList<Double>(); for(int i=1;i<header.size();i++){ qValues.add(Double.parseDouble(header.get(i))); } int n=0; while(br.readLine()!=null){ n++; } br.close(); double[][] probs=new double[n][qValues.size()]; br=new BufferedReader(new FileReader(randomDecoyFile)); br.readLine(); String line; n=0; while((line=br.readLine())!=null){ String[] l=line.split("\t"); for(int i=1;i<l.length;i++){ probs[n][i-1]=l[i].equals("null")?0.0:Double.parseDouble(l[i]); } n++; } for(int i=0;i<probs.length;i++){ double avg=0; double sum=0; for(int j=0;j<probs[i].length;j++){ avg+=qValues.get(j)*probs[i][j]; sum+=probs[i][j]; } avg/=sum; double s=0; sum=0; for(int j=0;j<probs[i].length;j++){ s+=Math.pow(qValues.get(j),2)*probs[i][j]; sum+=probs[i][j]; } s=Math.pow(s/sum-Math.pow(avg,2),0.5); result.add(new double[]{avg, s}); } br.close(); // BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); // bw.write("\testimated qValue\tstandard deviation"); // bw.newLine(); // for(int i=0;i<result.size();i++){ // bw.write(i+"\t"+result.get(i)[0]+"\t"+result.get(i)[1]); // bw.newLine(); // } // bw.close(); return result; } private static void outputMatrix(double[][] m, File outputFile) throws IOException{ BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); for(int j=0;j<m[0].length;j++){ bw.write("\t"+j); } bw.newLine(); for(int i=0;i<m.length;i++){ bw.write(Integer.toString(i)); for(int j=0;j<m[i].length;j++){ bw.write("\t"+m[i][j]); } bw.newLine(); } bw.close(); } static void createRandomDecoyQValues(int n, File randomDecoyFile) throws IOException { double[][] P=new double[n+1][n+1]; P[0][0]=1; for(int i=0;i<P.length;i++){ for(int k=0;k<P[i].length;k++){ if(i>0)P[i][k]+=P[i-1][k]*(n-i+1)/(2*n-i-k+1); if(k>0)P[i][k]+=P[i][k-1]*(n-k+1)/(2*n-i-k+1); } } double[][] D=new double[n][n+1]; for(int i=0;i<D.length;i++){ for(int k=0;k<D[i].length;k++){ // D[i][k]=P[i][k]*P[n-i-1][n-k]; D[i][k]=P[i][k]*(n-i)/(2*n-i-k); } } double[][] FDR=new double[n][n+1]; for(int i=0;i<FDR.length;i++){ for(int k=0;k<FDR[i].length;k++){ FDR[i][k]=1.0*k/(i+1); } } Map<Double, Double>[] valuesANDprobs=new Map[D.length]; for(int i=FDR.length-1;i>=0;i--){ long time=System.currentTimeMillis(); Map<Double, Double> currentMap=new HashMap<Double, Double>(); valuesANDprobs[i]=currentMap; Map<Double, Double> previousMap=new HashMap<Double, Double>(); if(i==FDR.length-1){ previousMap.put(Double.POSITIVE_INFINITY,1.0); }else{ previousMap=valuesANDprobs[i+1]; } for(Entry<Double,Double> entry:previousMap.entrySet()){ double d1=entry.getKey(); double prob1=entry.getValue(); for(int j=0;j<D[i].length;j++){ double d2=FDR[i][j]; double prob2=D[i][j]; double min=Math.round(Math.min(d1,d2)*1000)/1000.0; double currentProb=currentMap.containsKey(min)?currentMap.get(min):0.0; currentMap.put(min, currentProb+prob1*prob2); } } System.out.print(i+" "+currentMap.size()+" "+(System.currentTimeMillis()-time)/1000.0); System.out.println(); } BufferedWriter bw=new BufferedWriter(new FileWriter(randomDecoyFile)); Set<Double> allKeys=new TreeSet<Double>(); for(Map<Double,Double> v:valuesANDprobs){ allKeys.addAll(v.keySet()); } for(double d:allKeys)bw.write("\t"+d); bw.newLine(); for(int i=0;i<valuesANDprobs.length;i++){ Map<Double,Double> v=valuesANDprobs[i]; bw.write(Integer.toString(i)); for(double d:allKeys) bw.write("\t"+v.get(d)); bw.newLine(); } bw.close(); } } class Hit{ enum DataBase{Original, Decoy} DataBase db; MassBank massbankQuery; int numberEntries; List<MassBank> hitsInDB=new ArrayList<MassBank>(); Double scoreBestHit; Integer minRankBestHit; Integer maxRankBestHit; List<MassBank> bestNonHits=new ArrayList<MassBank>(); Double scoreBestNonHit; // List<MassBank> bestHits=null; public boolean isEmpty(){ return numberEntries==0; } public boolean noCorrectHit(){ return hitsInDB.isEmpty(); } public Double getBestScore(){ if(isEmpty())return null; return Math.max(scoreBestHit==null?Double.MIN_VALUE:scoreBestHit, scoreBestNonHit==null?Double.MIN_VALUE:scoreBestNonHit); } public Boolean correctHitMinRank(){ if(noCorrectHit())return false; return minRankBestHit==1; } public Double correctHitMediumRank(){ if(noCorrectHit()||!correctHitMinRank())return null; return 1.0/maxRankBestHit; } public Double getMediumRankBestHit(){ if(noCorrectHit())return null; return minRankBestHit+(maxRankBestHit-minRankBestHit)/2.0; } public Boolean correctHitMaxRank(){ if(noCorrectHit())return false; return maxRankBestHit==1; } } class HitComparator implements Comparator<Hit>{ enum SortAtEqualScore{BESTCASE, WORSTCASE}; SortAtEqualScore s=null; public HitComparator(SortAtEqualScore s){ this.s=s; } @Override public int compare(Hit o1, Hit o2) { int c=o2.getBestScore().compareTo(o1.getBestScore()); if(c!=0)return c; if(o1.db!=null&&o2.db!=null&&o1.db!=o2.db){ if(o2.db==Hit.DataBase.Decoy)return -1; return 1; } c=Boolean.compare(o2.correctHitMinRank(), o1.correctHitMinRank()); if(s.equals(SortAtEqualScore.BESTCASE)){ return c; } return -c; } }
33,716
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
Main.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/Main.java
package de.unijena.bioinf.statistics; public class Main { public static void main(String args[]) throws Exception{ String a="-base U:\\MSBlast\\ -ppm 10 -ae 2 -addFolder RPP " +"-queries " +"APFilesOriginal-GPTrees " +"-searchMethodsStatisticsOriginal MassBank " +"-searchMethods MassBank " +"-decoyMethods Reroot " // +"-getHitLists " // +"-statisticsOriginal " //// +"-getRankStatistic " //// +"-checkEquality " // +"-getQValues " // +"-getQValuesAverage " +"-getQValueSummary " //// +"-getQValueSummaryPerQValue " // +"-getQValueSummaryPerQValueEstimated " // +"-getQValueSummaryPerPosition " ; MainStatistics.main(a.split(" ")); } }
710
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
Result.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/Result.java
package de.unijena.bioinf.statistics; import de.unijena.bioinf.decoy.model.MassBank; public class Result implements Comparable<Result>{ String resultID; public int matchedPeaks; public double score; boolean isTrueMatch; MassBank massbank; public Result(String[] line){ resultID=line[1]; matchedPeaks=Integer.parseInt(line[3]); score=Double.parseDouble(line[4]); } public Result(int matchedPeaks, double score){ this.matchedPeaks=matchedPeaks; this.score=score; } public Result(String resultID, int matchedPeaks, double score){ this(matchedPeaks, score); this.resultID=resultID; } @Override public int compareTo(Result r) { return Double.compare(r.score,score); } public String getDB(){ return resultID.replaceAll("\\d",""); } public String getNumber(){ return resultID.replaceAll("\\D",""); } public String getDataset(){ return resultID.substring(0,1); } }
956
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
pValues.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/pValues.java
package de.unijena.bioinf.statistics; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import de.unijena.bioinf.em.EMUtils; import de.unijena.bioinf.em.Sample.Type; public class pValues { static String base="U:\\MSBlast\\"; public static void main(String args[]) throws Exception{ for(String compounds : new String[]{"Compounds"}){ // for(boolean log:new boolean[]{false,true}){ for(boolean log:new boolean[]{false}){ for(String comparisonMethod : new String[]{"MassBank", "CosineDistance"}){ // for(String comparisonMethod : new String[]{"MassBank"}){ for(String hs : new String[]{"DifferentMassesExcluded","DMEHighFDR"}){ // for(String hs : new String[]{"DifferentMassesExcluded"}){ for(String dataset : new String[]{"APFilesOriginal-GPFiles","APFilesOriginal-GPTrees","APTreesOriginal-GPTrees","OPFilesOriginal-GPFiles","OPFilesOriginal-GPTrees","OPTreesOriginal-GPTrees"}){ // for(String dataset : new String[]{"APFilesOriginal-GPFiles"}){ for(String decoydataset : new String[]{"ConditionalFast","MixedSpectrum","RandomPeaks","RandomTree","Reroot"}){ // for(String decoydataset : new String[]{"ConditionalFast"}){ File inputFolder=new File("U:\\MSBlast\\qValues_All"+compounds+"RPP\\pos\\MassBank\\HitStatistic_"+hs+"_"+dataset+decoydataset); if(!inputFolder.exists())continue; int selMax=1; if(compounds.equals("Selections")){ selMax=10; } int decoyMax=1; if(compounds.equals("Compounds")){ decoyMax=10; } List<Double> TP=new ArrayList<Double>(); List<Double> FP=new ArrayList<Double>(); List<Double> All=new ArrayList<Double>(); for(int sel=0;sel<selMax;sel++){ String addSel="_Selection"+sel; for(int decoy=1;decoy<decoyMax;decoy++){ String addDecoy="_"+decoy; File inputFile=new File("U:\\MSBlast\\qValues_All"+compounds+"RPP\\pos\\MassBank\\HitStatistic_"+hs+"_"+dataset+decoydataset+"\\QValues"+addSel+"_HitStatistic_"+hs+"_"+dataset+decoydataset+addDecoy+".hitlist"); if(!inputFile.exists())continue; BufferedReader br=new BufferedReader(new FileReader(inputFile)); br.readLine();br.readLine(); String line; int allDecoys=0; while((line=br.readLine())!=null){ String l[]=line.split("\t"); if(l[1].equals("DecoyMatch"))allDecoys++; } br.close(); br=new BufferedReader(new FileReader(inputFile)); br.readLine();br.readLine(); int numberDecoys=0; while((line=br.readLine())!=null){ String l[]=line.split("\t"); if(l[1].equals("DecoyMatch"))numberDecoys++; if(l[1].equals("TruePositiveMatch"))TP.add(1.0*numberDecoys/allDecoys); if(l[1].equals("FalsePositiveMatch"))FP.add(1.0*numberDecoys/allDecoys); if(!l[1].equals("DecoyMatch"))All.add(1.0*numberDecoys/allDecoys); } br.close(); } } for(int bins:new int[]{10,20,30}){ File outputFilePValuesAll=new File("U:\\MSBlast\\qValues_All"+compounds+"RPP\\pos\\MassBank\\HitStatistic_"+hs+"_"+dataset+decoydataset+"\\QValues_HitStatistic_"+hs+"_"+dataset+decoydataset+"_All_"+bins+"bins.pValues"); EMUtils.writePValues(outputFilePValuesAll, "All", All, bins); File outputFilePValuesFP=new File("U:\\MSBlast\\qValues_All"+compounds+"RPP\\pos\\MassBank\\HitStatistic_"+hs+"_"+dataset+decoydataset+"\\QValues_HitStatistic_"+hs+"_"+dataset+decoydataset+"_FP_"+bins+"bins.pValues"); EMUtils.writePValues(outputFilePValuesFP, "FP", FP, bins); File outputFilePValuesTP=new File("U:\\MSBlast\\qValues_All"+compounds+"RPP\\pos\\MassBank\\HitStatistic_"+hs+"_"+dataset+decoydataset+"\\QValues_HitStatistic_"+hs+"_"+dataset+decoydataset+"_TP_"+bins+"bins.pValues"); EMUtils.writePValues(outputFilePValuesTP, "TP", TP, bins); } System.out.print(""); } } } } } } } }
4,416
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MainStatistics.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/MainStatistics.java
package de.unijena.bioinf.statistics; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Shape; import java.awt.Stroke; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.swing.filechooser.FileFilter; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.DeviationRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.statistics.DefaultBoxAndWhiskerCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONMETHOD; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; import de.unijena.bioinf.statistics.HitStatistic.HitDescription; import de.unijena.bioinf.statistics.SimilarityMatrix.DatabaseType; //generating statistics public class MainStatistics { static String[] querys=new String[]{"APFilesOriginal-MPFiles","APFilesOriginal-MPTrees","APTreesOriginal-MPTrees","MPFilesOriginal-APFiles","MPFilesOriginal-APTrees","MPTreesOriginal-APTrees"}; static String[] searchMethodsStatisticsOriginal=new String[]{"CosineDistance"/*,"DBSearch"*/,"MassBank","OberacherWithIntensities","OberacherWithIntensitiesAndMasses","TreeAlignment"}; static String[] searchMethods=new String[]{"CosineDistance"/*,"DBSearch"*/,"MassBank"/*,"OberacherWithIntensities","OberacherWithIntensitiesAndMasses","TreeAlignment"*/}; static String[] decoyMethods=new String[]{"Original","RandomPeaks","MixedSpectrum"/*,"ConditionalPeaks"*/,"Reroot",/*"RandomTree",*/"ConditionalFast"/*,"RandomDecoy"*/}; static double ppm=10; static double ae=2; // static String msBlastFolder="U:\\MSBlast\\"; static String msBlastFolder="D:\\metabo_tandem_ms\\MSBlast\\"; static String addFolder=""; static String ser; static File[] originalDBFolders; static boolean getHitLists=false; static boolean statisticsOriginal=false; static boolean getRankStatistic=false; static boolean checkEquality=false; static boolean getQValues=false; static boolean getQValuesAverage=false; static boolean getQValueSummary=false; static boolean getQValueSummaryPerQValue=false; static boolean getQValueSummaryPerQValueEstimated=false; static boolean getQValueSummaryPerPosition=false; static final String sep=System.getProperty("file.separator"); public static void init(String[] args){ int i=0; if(args!=null){ while(i<args.length){ if(args[i].equals("-base"))msBlastFolder=args[++i]; if(args[i].equals("-addFolder"))addFolder=args[++i]; if(args[i].equals("-ppm"))ppm=Double.parseDouble(args[++i]); if(args[i].equals("-ae"))ae=Double.parseDouble(args[++i]); if(args[i].equals("-queries"))querys=args[++i].split(","); if(args[i].equals("-searchMethods"))searchMethods=args[++i].split(","); if(args[i].equals("-searchMethodsStatisticsOriginal"))searchMethodsStatisticsOriginal=args[++i].split(","); if(args[i].equals("-decoyMethods"))decoyMethods=args[++i].split(","); if(args[i].equals("-getHitLists"))getHitLists=true; if(args[i].equals("-statisticsOriginal"))statisticsOriginal=true; if(args[i].equals("-getRankStatistic"))getRankStatistic=true; if(args[i].equals("-checkEquality"))checkEquality=true; if(args[i].equals("-getQValues"))getQValues=true; if(args[i].equals("-getQValuesAverage"))getQValuesAverage=true; if(args[i].equals("-getQValueSummary"))getQValueSummary=true; if(args[i].equals("-getQValueSummaryPerQValue"))getQValueSummaryPerQValue=true; if(args[i].equals("-getQValueSummaryPerQValueEstimated"))getQValueSummaryPerQValueEstimated=true; if(args[i].equals("-getQValueSummaryPerPosition"))getQValueSummaryPerPosition=true; i++; } } ser=msBlastFolder+"Data"+sep+"originalDB.ser"; originalDBFolders=new File[]{ new File(msBlastFolder+"Data"+sep+"DataBases"+sep+"Agilent"+sep+"pos"+sep+"AgilentPositiveTreesOriginal"+sep+"massbank"), new File(msBlastFolder+"Data"+sep+"DataBases"+sep+"Agilent"+sep+"pos"+sep+"AgilentPositiveFilesOriginal"+sep+"massbank"), new File(msBlastFolder+"Data"+sep+"DataBases"+sep+"Massbank"+sep+"pos"+sep+"MassbankPositiveTreesOriginal"+sep+"massbank"), new File(msBlastFolder+"Data"+sep+"DataBases"+sep+"Massbank"+sep+"pos"+sep+"MassbankPositiveFilesOriginal"+sep+"massbank"), new File(msBlastFolder+"Data"+sep+"DataBases"+sep+"MassbankOrbi"+sep+"pos"+sep+"MassbankOrbiPositiveTreesOriginal"+sep+"massbank"), new File(msBlastFolder+"Data"+sep+"DataBases"+sep+"MassbankOrbi"+sep+"pos"+sep+"MassbankOrbiPositiveFilesOriginal"+sep+"massbank"), new File(msBlastFolder+"Data"+sep+"DataBases"+sep+"MassbankQTof"+sep+"pos"+sep+"MassbankQTofPositiveTreesOriginal"+sep+"massbank"), new File(msBlastFolder+"Data"+sep+"DataBases"+sep+"MassbankQTof"+sep+"pos"+sep+"MassbankQTofPositiveFilesOriginal"+sep+"massbank"), new File(msBlastFolder+"Data"+sep+"DataBases"+sep+"Gnps"+sep+"pos"+sep+"GnpsPositiveTreesOriginal"+sep+"massbank"), new File(msBlastFolder+"Data"+sep+"DataBases"+sep+"Gnps"+sep+"pos"+sep+"GnpsPositiveFilesOriginal"+sep+"massbank") }; } public static void main(String args[]) throws Exception{ init(args); File searchResultsFile=new File(msBlastFolder+"searchResults"+addFolder); if(!searchResultsFile.exists())searchResultsFile.mkdirs(); File statisticsFile=new File(msBlastFolder+"statistics"+addFolder+sep+"pos"); if(!statisticsFile.exists())statisticsFile.mkdirs(); File graphicsFile=new File(msBlastFolder+sep+"graphics_Statistics"+addFolder+sep+"pos"); if(!graphicsFile.exists())graphicsFile.mkdirs(); if(getHitLists)getHitLists(searchResultsFile,statisticsFile); if(statisticsOriginal){ statisticsOriginal(statisticsFile, new File(statisticsFile.getAbsolutePath()+sep+"statOriginal.txt"), new File (statisticsFile.getAbsolutePath()+sep+"changesOriginal.txt"), graphicsFile); statisticsHighFDR(statisticsFile, new File(statisticsFile.getAbsolutePath()+sep+"statOriginalDMEHighFDR.txt"), new File (statisticsFile.getAbsolutePath()+sep+"changesOriginalDMEHighFDR.txt"), graphicsFile); } if(getRankStatistic)getRankStatistic(searchResultsFile,graphicsFile); if(checkEquality)checkEquality(searchResultsFile,graphicsFile); for(int i:new int[]{1,5}){ String add=""; if(i==1)add="_AllCompounds"; if(i==5)add="_AllSelections"; File qValuesFileAdd=new File(msBlastFolder+"qValues"+add+addFolder+sep+"pos"); if(!qValuesFileAdd.exists())qValuesFileAdd.mkdirs(); File graphicsFileAdd=new File(msBlastFolder+"graphics"+add+addFolder+sep+"pos"); if(!graphicsFileAdd.exists())graphicsFileAdd.mkdirs(); if(getQValues)getQValues(i, statisticsFile, qValuesFileAdd); if(getQValuesAverage)getQValuesAverage(qValuesFileAdd); if(getQValueSummary)getQValueSummary(new double[]{/*0,0,*/0,0},new double[]{/*0.01,0.05,*/0.1,1},qValuesFileAdd,graphicsFileAdd); if(getQValueSummaryPerQValue)getQValueSummaryPerQValue(new double[]{/*0,0,*/0,0},new double[]{/*0.01,0.05,*/0.1,1}, qValuesFileAdd, graphicsFileAdd, graphicsFileAdd, true); if(getQValueSummaryPerQValueEstimated)getQValueSummaryPerQValue(new double[]{/*0,0,*/0,0},new double[]{/*0.01,0.05,*/0.1,1}, qValuesFileAdd, graphicsFileAdd, graphicsFileAdd, false); if(getQValueSummaryPerPosition)getQValueSummaryPerPosition(new double[]{/*0,0,*/0,0},new double[]{/*0.1,0.3,*/0.5,1},qValuesFileAdd, graphicsFileAdd, graphicsFileAdd); } System.out.println("FINISHED"); } private static void getQValuesAverage(File outputFileQValues) throws Exception{ Locale.setDefault(Locale.US); DecimalFormat df=new DecimalFormat("0.00"); for(String masses:new String[]{"HitStatistic_DifferentMassesExcluded_","HitStatistic_DMEHighFDR_"}){ // BufferedWriter bw=new BufferedWriter(new FileWriter(new File(outputFileQValues.getAbsolutePath()+sep+masses+"qValueSummary_"+df.format(minQValue)+"-"+df.format(maxQValue)+".txt"))); List<String> dataset=new ArrayList<String>(); List<String> lines=new ArrayList<String>(); List<String> rows=new ArrayList<String>(); // searchMethods=new String[]{"CosineDistance"}; // querys=new String[]{"APFilesOriginal-MPFiles"}; // decoyMethods=new String[]{"RandomPeaks"}; for(String query:querys)dataset.add(query); for(String searchMethod:searchMethods)lines.add(searchMethod); for(String s:decoyMethods)if(!s.equals("Original"))rows.add(s); for (int i=0;i<querys.length;i++){ String queryLong=querys[i]; for(String searchMethod:searchMethods){ for(String s:decoyMethods){ if(s.equals("Original"))continue; File qValueFolderSelection=new File(outputFileQValues.getAbsolutePath()+sep+searchMethod+sep+masses+queryLong+s); if(!qValueFolderSelection.exists())continue; System.out.println(qValueFolderSelection.getAbsolutePath()); getQValuesAverage(Arrays.asList(qValueFolderSelection.listFiles(new FileExtensionFilter("qValueMean"))),"Mean"); getQValuesAverage(Arrays.asList(qValueFolderSelection.listFiles(new FileExtensionFilter("qValueMergeMean"))),"MergeMean"); } } } } } private static void getQValueSummary(double[] minQValues, double[] maxQValues, File outputFileQValues, File outputFileGraphics) throws Exception{ Locale.setDefault(Locale.US); DecimalFormat df=new DecimalFormat("0.00"); for(int q=0;q<minQValues.length;q++){ double minQValue=minQValues[q]; double maxQValue=maxQValues[q]; for(boolean normalizedEstimated:new boolean[]{true, false}){ for(String extension:new String[]{"qValue","qValueMean","qValueMerge","qValueMergeMean","qValueMeanAverage","qValueMergeMeanAverage"}){ if(extension.contains("Merge")&&normalizedEstimated)continue; for(String masses:new String[]{"HitStatistic_DifferentMassesExcluded_","HitStatistic_DMEHighFDR_"}){ // BufferedWriter bw=new BufferedWriter(new FileWriter(new File(outputFileQValues.getAbsolutePath()+sep+masses+"qValueSummary_"+df.format(minQValue)+"-"+df.format(maxQValue)+".txt"))); List<String> dataset=new ArrayList<String>(); List<String> lines=new ArrayList<String>(); List<String> rows=new ArrayList<String>(); // searchMethods=new String[]{"CosineDistance"}; // querys=new String[]{"APFilesOriginal-MPFiles"}; // decoyMethods=new String[]{"RandomPeaks"}; for(String query:querys)dataset.add(query); for(String searchMethod:searchMethods)lines.add(searchMethod); for(String s:decoyMethods)if(!s.equals("Original"))rows.add(s); for (int i=0;i<querys.length;i++){ String queryLong=querys[i]; for(String searchMethod:searchMethods){ XYSeriesCollection ds = new XYSeriesCollection(); XYSeries seriesWH=SimilarityMatrix.getBisectingLine(minQValue, maxQValue); ds.addSeries(seriesWH); for(String s:decoyMethods){ if(s.equals("Original"))continue; File qValueFolderSelection=new File(outputFileQValues.getAbsolutePath()+sep+searchMethod+sep+masses+queryLong+s); if(!qValueFolderSelection.exists())continue; System.out.println(qValueFolderSelection.getName()); double[] v=getAverageDistance(Arrays.asList(qValueFolderSelection.listFiles(new FileExtensionFilter(extension))), minQValue, maxQValue, normalizedEstimated); // results[dataset.indexOf(queryLong)][lines.indexOf(searchMethod)][rows.indexOf(s)]=v; File f=new File(outputFileGraphics.getAbsolutePath()+sep+searchMethod+sep+"qValues"+(normalizedEstimated?"_norm":"")+sep+extension+sep+masses+queryLong+s+"_"+df.format(minQValue)+"-"+df.format(maxQValue)+".jpg"); if(!f.getParentFile().exists())f.getParentFile().mkdirs(); List<double[]> averageQValues=writeQValues(f, Arrays.asList(qValueFolderSelection.listFiles(new FileExtensionFilter(extension))), minQValue, maxQValue, normalizedEstimated); // File txt =new File(outputFileGraphics.getAbsoluteFile()+sep+searchMethod+sep+"qValues"+(normalizedEstimated?"_norm":"")+sep+extension+sep+masses+"Average_"+s+"_"+queryLong+"_"+df.format(minQValue)+"-"+df.format(maxQValue)+".txt"); // BufferedWriter bw=new BufferedWriter(new FileWriter(txt)); // bw.write("real qValue\testimated qValue ("+s+")"); // bw.newLine(); XYSeries xyseries=new XYSeries(s); for(double[] e:averageQValues){ xyseries.add(e[0], e[1]); // bw.write(e[0]+"\t"+e[1]); // bw.newLine(); } ds.addSeries(xyseries); // bw.close(); System.out.println("getQValueSummary: " + (normalizedEstimated?"_norm":"") + " "+searchMethod+" "+queryLong+s+" "+v[0]+" "+v[1]+" "+v[2]); } if(ds.getSeries().size()>1){ File jpg =new File(outputFileGraphics.getAbsoluteFile()+sep+searchMethod+sep+"qValues"+(normalizedEstimated?"_norm":"")+sep+extension+sep+masses+"Joint_"+queryLong+"_"+df.format(minQValue)+"-"+df.format(maxQValue)+".jpg"); if(!jpg.getParentFile().exists())jpg.getParentFile().mkdirs(); final JFreeChart chart =ChartFactory.createScatterPlot("averageQValues", "qValue calculated", "qValue by decoy database",ds); ChartUtilities.saveChartAsJPEG(jpg, chart, 1000, 1000); } System.out.println(); } } } } } } } private static void getQValueSummaryPerQValue(double[] minQValues, double[] maxQValues, File inputFileQValues, File outputFileQValues, File outputFileGraphics, boolean useRealQValue) throws Exception{ Locale.setDefault(Locale.US); Stroke dashedStroke = new BasicStroke( 1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] {10.0f, 6.0f}, 0.0f ); DecimalFormat df=new DecimalFormat("0.00"); for(int q=0;q<minQValues.length;q++){ double minQValue=minQValues[q]; double maxQValue=maxQValues[q]; for(boolean normalizedEstimated:new boolean[]{false, true}){ for(String extension:new String[]{"qValue","qValueMerge","qValueAverage"}){ if(extension.equals("qValueMerge")&&normalizedEstimated)continue; for(String masses:new String[]{"HitStatistic_DifferentMassesExcluded_","HitStatistic_DMEHighFDR_"}){ List<String> dataset=new ArrayList<String>(); List<String> lines=new ArrayList<String>(); List<String> rows=new ArrayList<String>(); // searchMethods=new String[]{"CosineDistance"}; // querys=new String[]{"APFilesOriginal-MPFiles"}; // decoyMethods=new String[]{"RandomPeaks"}; for(String query:querys)dataset.add(query); for(String searchMethod:searchMethods)lines.add(searchMethod); for(String s:decoyMethods)if(!s.equals("Original"))rows.add(s); Map<String,TreeMap<Double,double[]>> results[][][]=new Map[dataset.size()][lines.size()][rows.size()]; for (int k=0;k<dataset.size();k++){ String queryLong=dataset.get(k); for(int i=0;i<lines.size();i++){ String searchMethod=lines.get(i); Set<String> outputs=new HashSet<String>(); for(int j=0;j<rows.size();j++){ String s=rows.get(j); if(s.equals("Original"))continue; File qValueFolderSelection=new File(inputFileQValues.getAbsolutePath()+sep+searchMethod+sep+masses+queryLong+s); if(!qValueFolderSelection.exists())continue; Map<String,TreeMap<Double,double[]>> v=getAverageDistancePerQValue(minQValue, maxQValue, useRealQValue, Arrays.asList(qValueFolderSelection.listFiles(new FileExtensionFilter(extension))), normalizedEstimated); results[k][i][j]=v; outputs.addAll(v.keySet()); System.out.println("getQValueSummaryPerQValue: " +(normalizedEstimated?"_norm":"")+useRealQValue+" "+ searchMethod+" "+queryLong+s); } for(String o:outputs){ File txtFile=new File(outputFileQValues.getAbsolutePath()+sep+lines.get(i)+sep+"qValuePerQValue"+(useRealQValue?"":"Estimated")+(normalizedEstimated?"_norm":"")+sep+extension+sep+masses+"qValuePerQValueSummary_"+dataset.get(k)+"_"+lines.get(i)+"_"+df.format(minQValue)+"-"+df.format(maxQValue)+o+".txt"); if(!txtFile.getParentFile().exists())txtFile.getParentFile().mkdirs(); BufferedWriter bw=new BufferedWriter(new FileWriter(txtFile)); for(int j=0;j<rows.size();j++){ if(results[k][i][j]!=null&&results[k][i][j]!=null)bw.write("\t"+lines.get(i)+"_"+rows.get(j)+" average\t"+lines.get(i)+"_"+rows.get(j)+" standard deviation"); } bw.newLine(); XYSeriesCollection col = new XYSeriesCollection(); XYSeriesCollection colAvgDev = new XYSeriesCollection(); TreeSet<Double> s=new TreeSet<Double>(); XYSeries[][] series = new XYSeries[lines.size()][rows.size()]; XYSeries[][][] seriesAvgDev = new XYSeries[lines.size()][rows.size()][3]; for(int j=0;j<rows.size();j++){ if(results[k][i][j]==null||results[k][i][j].get(o)==null)continue; s.addAll(results[k][i][j].get(o).keySet()); series[i][j]=new XYSeries(lines.get(i)+"_"+rows.get(j)); if(!rows.get(j).equals("RandomDecoy"))col.addSeries(series[i][j]); seriesAvgDev[i][j][0]=new XYSeries(lines.get(i)+"_"+rows.get(j)+" standard deviation -"); seriesAvgDev[i][j][1]=new XYSeries(lines.get(i)+"_"+rows.get(j)+" average"); seriesAvgDev[i][j][2]=new XYSeries(lines.get(i)+"_"+rows.get(j)+" standard deviation +"); if(!rows.get(j).equals("RandomDecoy"))colAvgDev.addSeries(seriesAvgDev[i][j][0]); if(!rows.get(j).equals("RandomDecoy"))colAvgDev.addSeries(seriesAvgDev[i][j][1]); if(!rows.get(j).equals("RandomDecoy"))colAvgDev.addSeries(seriesAvgDev[i][j][2]); } for(Double key:s){ bw.write(Double.toString(key)); for(int j=0;j<rows.size();j++){ if(results[k][i][j]==null||results[k][i][j].get(o)==null)continue; bw.write("\t"); Double[] d =new Double[]{null,null,null}; Entry<Double, double[]> tmp=results[k][i][j].get(o).floorEntry(key); if(tmp!=null){ double v[] =tmp.getValue(); d=new Double[]{v[0],v[1]}; bw.write(Double.toString(d[0])+"\t"+Double.toString(d[1])); series[i][j].add(key,new Double(d[0])); seriesAvgDev[i][j][0].add(key,new Double(d[0]-d[1])); seriesAvgDev[i][j][1].add(key,new Double(d[0])); seriesAvgDev[i][j][2].add(key,new Double(d[0]+d[1])); }else{ bw.write("null"); } } bw.newLine(); } bw.close(); File jpg =new File(outputFileGraphics.getAbsolutePath()+sep+lines.get(i)+sep+"qValuePerQValue"+(useRealQValue?"":"Estimated")+(normalizedEstimated?"_norm":"")+sep+extension+sep+masses+"qValuePerQValue_"+dataset.get(k)+"_"+lines.get(i)+"_"+df.format(minQValue)+"-"+df.format(maxQValue)+o+".jpg"); if(!jpg.getParentFile().exists())jpg.getParentFile().mkdirs(); JFreeChart chart =ChartFactory.createXYLineChart("qValuePerQValue", (useRealQValue?"real":"estimated")+" qValue", "difference", col); ChartUtilities.saveChartAsJPEG(jpg, chart, 1000, 1000); jpg =new File(outputFileGraphics.getAbsolutePath()+sep+lines.get(i)+sep+"qValuePerQValue"+(useRealQValue?"":"Estimated")+(normalizedEstimated?"_norm":"")+sep+extension+sep+masses+"qValuePerQValue_"+dataset.get(k)+"_"+lines.get(i)+"_"+df.format(minQValue)+"-"+df.format(maxQValue)+o+"_AvgDev.jpg"); if(!jpg.getParentFile().exists())jpg.getParentFile().mkdirs(); chart =ChartFactory.createXYLineChart("qValuePerQValue", (useRealQValue?"real":"estimated")+" qValue", "difference", colAvgDev); XYPlot plot = (XYPlot) chart.getPlot(); XYLineAndShapeRenderer renderer = new DeviationRenderer(true, false); Color[] c=new Color[]{Color.BLUE, Color.CYAN, Color.RED, Color.GREEN, Color.ORANGE, Color.PINK, Color.YELLOW, Color.MAGENTA}; for(int j=0;j<rows.size();j++){ renderer.setSeriesPaint(j*3, c[j%c.length] ); renderer.setSeriesStroke(j*3, dashedStroke); renderer.setSeriesPaint(j*3+1, c[j%c.length]); renderer.setSeriesStroke(j*3+2, dashedStroke); renderer.setSeriesPaint(j*3+2, c[j%c.length]); } plot.setRenderer(renderer); ChartUtilities.saveChartAsJPEG(jpg, chart, 1000, 1000); } } } } } } } } private static void getQValueSummaryPerPosition(double[] minQValues, double[] maxQValues, File inputFileQValues, File outputFileQValues, File outputFileGraphics) throws Exception{ Locale.setDefault(Locale.US); Stroke dashedStroke = new BasicStroke( 1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] {10.0f, 6.0f}, 0.0f ); DecimalFormat df=new DecimalFormat("0.00"); for(int q=0;q<minQValues.length;q++){ double minQValue=minQValues[q]; double maxQValue=maxQValues[q]; for(boolean normalizedEstimated:new boolean[]{false, true}){ for(String extension:new String[]{"qValue","qValueMerge","qValueAverage"}){ if(extension.equals("qValueMerge")&&normalizedEstimated)continue; for(String masses:new String[]{"HitStatistic_DifferentMassesExcluded_","HitStatistic_DMEHighFDR_"}){ List<String> dataset=new ArrayList<String>(); List<String> lines=new ArrayList<String>(); List<String> rows=new ArrayList<String>(); // searchMethods=new String[]{"CosineDistance"}; // querys=new String[]{"APFilesOriginal-MPFiles"}; // decoyMethods=new String[]{"RandomPeaks"}; for(String query:querys)dataset.add(query); for(String searchMethod:searchMethods)lines.add(searchMethod); for(String s:decoyMethods)if(!s.equals("Original"))rows.add(s); Map<String, TreeMap<Double, double[]>> results[][][]=new HashMap[dataset.size()][lines.size()][rows.size()]; for (int k=0;k<dataset.size();k++){ String queryLong=dataset.get(k); for(int i=0;i<lines.size();i++){ String searchMethod=lines.get(i); Set<String> outputs=new HashSet<String>(); for(int j=0;j<rows.size();j++){ String s=rows.get(j); if(s.equals("Original"))continue; File qValueFolderSelection=new File(inputFileQValues.getAbsoluteFile()+sep+searchMethod+sep+masses+queryLong+s); if(!qValueFolderSelection.exists())continue; Map<String,TreeMap<Double,double[]>> v=getAverageDistancePerPosition(minQValue, maxQValue, Arrays.asList(qValueFolderSelection.listFiles(new FileExtensionFilter(extension))), normalizedEstimated); results[k][i][j]=v; outputs.addAll(v.keySet()); System.out.println("getQValueSummaryPerPosition: "+(normalizedEstimated?"_norm":"")+ searchMethod+" "+queryLong+s); } for(String o:outputs){ File txtFile=new File(outputFileQValues.getAbsolutePath()+sep+lines.get(i)+sep+"qValuePerPosition"+(normalizedEstimated?"_norm":"")+sep+extension+sep+masses+"qValuePerPositionSummary_"+dataset.get(k)+"_"+lines.get(i)+"_"+df.format(minQValue)+"-"+df.format(maxQValue)+o+".txt"); if(!txtFile.getParentFile().exists())txtFile.getParentFile().mkdirs(); BufferedWriter bw=new BufferedWriter(new FileWriter(txtFile)); for(int j=0;j<rows.size();j++){ if(results[k][i][j]!=null&&results[k][i][j].get(o)!=null)bw.write("\t"+lines.get(i)+"_"+rows.get(j)+" average\t"+lines.get(i)+"_"+rows.get(j)+" standard deviation"); } bw.newLine(); XYSeriesCollection col = new XYSeriesCollection(); XYSeriesCollection colAvgDev = new XYSeriesCollection(); double max=0; XYSeries[][] series = new XYSeries[lines.size()][rows.size()]; XYSeries[][][] seriesAvgDev = new XYSeries[lines.size()][rows.size()][3]; for(int j=0;j<rows.size();j++){ if(results[k][i][j]==null||results[k][i][j].get(o)==null)continue; max=Math.max(max,results[k][i][j].get(o).size()); series[i][j]=new XYSeries(lines.get(i)+"_"+rows.get(j)); if(!rows.get(j).equals("RandomDecoy"))col.addSeries(series[i][j]); seriesAvgDev[i][j][0]=new XYSeries(lines.get(i)+"_"+rows.get(j)+" standard deviation -"); seriesAvgDev[i][j][1]=new XYSeries(lines.get(i)+"_"+rows.get(j)+" average"); seriesAvgDev[i][j][2]=new XYSeries(lines.get(i)+"_"+rows.get(j)+" standard deviation +"); if(!rows.get(j).equals("RandomDecoy"))colAvgDev.addSeries(seriesAvgDev[i][j][0]); if(!rows.get(j).equals("RandomDecoy"))colAvgDev.addSeries(seriesAvgDev[i][j][1]); if(!rows.get(j).equals("RandomDecoy"))colAvgDev.addSeries(seriesAvgDev[i][j][2]); } for(double s=0;s<max;s++){ bw.write(Double.toString(s)); for(int j=0;j<rows.size();j++){ if(results[k][i][j]==null||results[k][i][j].get(o)==null)continue; bw.write("\t"); if(s<results[k][i][j].get(o).size()){ double[] d=results[k][i][j].get(o).get(s); if(d!=null){ bw.write(Double.toString(d[0])+"\t"+Double.toString(d[1])); series[i][j].add(s,new Double(d[0])); seriesAvgDev[i][j][0].add(s,new Double(d[0]-d[1])); seriesAvgDev[i][j][1].add(s,new Double(d[0])); seriesAvgDev[i][j][2].add(s,new Double(d[0]+d[1])); } } } bw.newLine(); } bw.close(); File jpg =new File(outputFileGraphics.getAbsolutePath()+sep+lines.get(i)+sep+"qValuePerPosition"+(normalizedEstimated?"_norm":"")+sep+extension+sep+masses+"qValuePerPosition_"+dataset.get(k)+"_"+lines.get(i)+"_"+df.format(minQValue)+"-"+df.format(maxQValue)+o+".jpg"); if(!jpg.getParentFile().exists())jpg.getParentFile().mkdirs(); JFreeChart chart =ChartFactory.createXYLineChart("qValuePerPosition", "qValue", "difference", col); ChartUtilities.saveChartAsJPEG(jpg, chart, 1000, 1000); jpg =new File(outputFileGraphics.getAbsolutePath()+sep+lines.get(i)+sep+"qValuePerPosition"+(normalizedEstimated?"_norm":"")+sep+extension+sep+masses+"qValuePerPosition_"+dataset.get(k)+"_"+lines.get(i)+"_"+df.format(minQValue)+"-"+df.format(maxQValue)+o+"_AvgDev.jpg"); if(!jpg.getParentFile().exists())jpg.getParentFile().mkdirs(); chart =ChartFactory.createXYLineChart("qValuePerPosition", "qValue", "difference", colAvgDev); XYPlot plot = (XYPlot) chart.getPlot(); XYLineAndShapeRenderer renderer = new DeviationRenderer(true, false); Color[] c=new Color[]{Color.BLUE, Color.CYAN, Color.RED, Color.GREEN, Color.ORANGE, Color.PINK, Color.YELLOW, Color.MAGENTA}; for(int j=0;j<rows.size();j++){ renderer.setSeriesPaint(j*3, c[j%c.length] ); renderer.setSeriesStroke(j*3, dashedStroke); renderer.setSeriesPaint(j*3+1, c[j%c.length]); renderer.setSeriesStroke(j*3+2, dashedStroke); renderer.setSeriesPaint(j*3+2, c[j%c.length]); } plot.setRenderer(renderer); ChartUtilities.saveChartAsJPEG(jpg, chart, 1000, 1000); } } } } } } } } public static List<List<double[]>> getPoints(List<File> inputFiles, double minQValue, double maxQValue, boolean realQValue, boolean decoyQValue, String op, boolean percentage, boolean normalizedEstimated) throws Exception{ List<List<double[]>> result=new ArrayList<List<double[]>>(); int all=0; for(File f:inputFiles){ BufferedReader br=new BufferedReader(new FileReader(f)); String line=br.readLine(); if(!line.contains("\t"))line=br.readLine(); int allTmp=0; while((line=br.readLine())!=null)allTmp++; all=Math.max(all, allTmp); br.close(); } for(File f:inputFiles){ List<double[]> tmp=new ArrayList<double[]>(); result.add(tmp); BufferedReader br=new BufferedReader(new FileReader(f)); String line=br.readLine(); if(!line.contains("\t")||line.split("\t").length>2)line=br.readLine(); List<String> header=Arrays.asList(line.split("\t")); int indexCalc=header.indexOf("calculated qValue"); int indexEst=header.indexOf("estimated qValue"); int n=0; double maxCalc=0; List<double[]> ds=new ArrayList<double[]>(); while((line=br.readLine())!=null){ String[] l=line.split("\t"); double calc=Double.parseDouble(l[indexCalc]); double est=Double.parseDouble(l[indexEst]); ds.add(new double[]{calc, est}); maxCalc=Math.max(maxCalc,calc); } if(normalizedEstimated){ for(double[] d:ds)d[1]/=maxCalc; } for(double[] d:ds){ double calc=d[0]; double est=d[1]; boolean add=op.equals("or")? ((!decoyQValue||(est>=minQValue&&est<=maxQValue))||(!realQValue||(calc>=minQValue&&calc<=maxQValue))): ((!decoyQValue||(est>=minQValue&&est<=maxQValue))&&(!realQValue||(calc>=minQValue&&calc<=maxQValue))); if(percentage){ double p=1.0*n/all; add=(p>=minQValue&&p<=maxQValue); } if(add){ tmp.add(d); } n++; } br.close(); } return result; } private static List<double[]> writeQValues(File outputFile, List<File> inputFiles, double minQValue, double maxQValue, boolean normalizedEstimated) throws Exception{ List<List<double[]>> r=getPoints(inputFiles, minQValue, maxQValue, true, false, "and", false, normalizedEstimated); Map<Integer,Map<Double, List<Double>>> allValues=new HashMap<Integer,Map<Double, List<Double>>>(); XYSeriesCollection dataset = new XYSeriesCollection(); List<double[]> result=new ArrayList<double[]>(); for(int i=0;i<inputFiles.size();i++){ XYSeries xyseries=new XYSeries(inputFiles.get(i).getName()); for(int j=0;j<r.get(i).size();j++){ double[] d=r.get(i).get(j); xyseries.add(d[0],d[1]); result.add(new double[]{d[0],d[1]}); if(!allValues.containsKey(j))allValues.put(j,new TreeMap<Double,List<Double>>()); if(!allValues.get(j).containsKey(d[0]))allValues.get(j).put(d[0], new ArrayList<Double>()); allValues.get(j).get(d[0]).add(d[1]); } dataset.addSeries(xyseries); } Collections.sort(result,new Comparator<double[]>(){ @Override public int compare(double[] o1, double[] o2) { int c=Double.compare(o1[0],o2[0]); if(c!=0)return c; return Double.compare(o1[1],o2[1]); } }); XYSeries seriesWH=SimilarityMatrix.getBisectingLine(minQValue, maxQValue); dataset.addSeries(seriesWH); final JFreeChart chart = ChartFactory.createScatterPlot("qValue", "qValue calculated", "qValue by decoy database", dataset, PlotOrientation.VERTICAL, false, false, false); ChartUtilities.saveChartAsJPEG(outputFile, chart, 1000, 1000); return result; } private static List<List<double[]>> getQValuesAverage(List<File> inputFiles, String add) throws Exception{ Map<String,List<File>> sortedFiles=new HashMap<String, List<File>>(); for(File f:inputFiles){ String name=f.getName(); name=name.replaceAll("Selection\\d*_",""); String id=f.getParent()+sep+name.substring(0,name.lastIndexOf('_'))+".qValue"+add+"Average"; if(!sortedFiles.containsKey(id))sortedFiles.put(id,new ArrayList<File>()); sortedFiles.get(id).add(f); } List<List<double[]>> result=new ArrayList<List<double[]>>(); for(Entry<String,List<File>> f:sortedFiles.entrySet()){ List<List<double[]>> r=getPoints(f.getValue(), Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, true, true, "and", false, false); Set<Double> keys=new TreeSet<Double>(); for(List<double[]> dl:r){ for(double d[]:dl){ keys.add(d[0]); } } List<double[]> res=new ArrayList<double[]>(); List<List<Double>> p=new ArrayList<List<Double>>(); for(double k:keys){ List<Double> points=new ArrayList<Double>(); for(List<double[]> dl:r){ for(int i=1;i<dl.size();i++){ double k_i=dl.get(i-1)[0]; double v_i=dl.get(i-1)[1]; double k_j=dl.get(i)[0]; double v_j=dl.get(i)[1]; if(k_i==k_j)continue; if(k_j>=k){ double m=(v_i-v_j)/(k_i-k_j); double n=v_i-m*k_i; points.add(m*k+n); break; } if(i==dl.size()-1){ points.add(v_j); } } } // for(double d:points)System.out.println(d); // System.out.println(); double[] as=getAverageAndStandardDeviation(points); p.add(points); res.add(new double[]{k,as[0],as[1]}); } BufferedReader br=new BufferedReader(new FileReader(f.getValue().get(0))); BufferedWriter bw=new BufferedWriter(new FileWriter(f.getKey())); bw.write(br.readLine()); br.close(); bw.newLine(); bw.write("calculated qValue\testimated qValue\tstandard deviation\tall values"); bw.newLine(); for(int i=0;i<res.size();i++){ double[] entry=res.get(i); List<Double> entryPoints=p.get(i); bw.write(entry[0]+"\t"+entry[1]+"\t"+entry[2]+"\t"); for(int j=0;j<entryPoints.size();j++){ double d=entryPoints.get(j); bw.write(d+""); if(j!=entryPoints.size()-1)bw.write(","); } bw.newLine(); } bw.close(); result.add(res); } return result; } private static double[] getAverageDistance(List<File> inputFiles, double minQValue, double maxQValue, boolean normalizedEstimated) throws Exception{ List<Double> avgs=new ArrayList<Double>(); List<List<double[]>> r=getPoints(inputFiles, minQValue, maxQValue, true, false, "and", false, normalizedEstimated); int points=0; for(List<double[]> l:r){ double sumTmp=0; int numberTmp=0; for(double[] d:l){ double calc=d[0]; double est=d[1]; double abw=Math.pow(calc-est,2); sumTmp+=abw; numberTmp++; } double avg=sumTmp/numberTmp; points+=numberTmp; avgs.add(avg); } double sum=0; for(double a:avgs){ sum+=a; } double avg=sum/avgs.size(); double s=0; for(double a:avgs){ s+=Math.pow(a-avg,2); } s=Math.pow(s/(avgs.size()-1), 0.5); return new double[]{1.0*points/avgs.size(), avg, s}; } private static Map<String, TreeMap<Double, double[]>> getAverageDistancePerQValue(double minQValue, double maxQValue, boolean useRealQValue, List<File> inputFiles, boolean normalizedEstimated) throws Exception{ List<List<double[]>> r=null; if(useRealQValue)r=getPoints(inputFiles, minQValue, maxQValue, true, false, "and", false, normalizedEstimated); if(!useRealQValue){ r=getPoints(inputFiles, minQValue, maxQValue, false, true, "and", false, normalizedEstimated); for(List<double[]> dl:r){ for(double[] d:dl){ double tmp=d[0]; d[0]=d[1]; d[1]=tmp; } } } Map<String, TreeMap<Double, double[]>> result = getResultDataStructure(r); for(Double qValueReal:result.get("_square").keySet()){ Map<String, Map<String, List<Double>>> points = getPointsDataStructure(inputFiles); for(int i=0;i<inputFiles.size();i++){ List<double[]> dl=r.get(i); String[] n=inputFiles.get(i).getName().substring(0,inputFiles.get(i).getName().lastIndexOf(".")).split("_"); double[] point=new double[]{0,0}; Iterator<double[]> it=dl.iterator(); while(it.hasNext()){ double d[]=it.next(); if(d[0]>qValueReal) break; point=d; it.remove(); } dl.add(0,point); double square=Math.pow(point[1]-point[0],2); double abs=Math.abs(point[1]-point[0]); double minus=point[1]-point[0]; points.get("minus").get("").add(minus); points.get("square").get("").add(square); points.get("abs").get("").add(abs); points.get("absPerSelection").get(n[1]).add(abs); points.get("squarePerSelection").get(n[1]).add(square); points.get("minusPerSelection").get(n[1]).add(minus); if(n.length==5){ points.get("absPerDB").get(n[4]).add(abs); points.get("squarePerDB").get(n[4]).add(square); points.get("minusPerDB").get(n[4]).add(minus); }else{ points.get("absPerDB").get("").add(abs); points.get("squarePerDB").get("").add(square); points.get("minusPerDB").get("").add(minus); } } result.get("_square").put(qValueReal, getAverageAndStandarddeviation(points.get("square"))); result.get("_squarePerDB").put(qValueReal, getAverageAndStandarddeviation(points.get("squarePerDB"))); result.get("_squarePerSelection").put(qValueReal, getAverageAndStandarddeviation(points.get("squarePerSelection"))); result.get("_abs").put(qValueReal, getAverageAndStandarddeviation(points.get("abs"))); result.get("_absPerDB").put(qValueReal, getAverageAndStandarddeviation(points.get("absPerDB"))); result.get("_absPerSelection").put(qValueReal, getAverageAndStandarddeviation(points.get("absPerSelection"))); result.get("_minus").put(qValueReal, getAverageAndStandarddeviation(points.get("minus"))); result.get("_minusPerDB").put(qValueReal, getAverageAndStandarddeviation(points.get("minusPerDB"))); result.get("_minusPerSelection").put(qValueReal, getAverageAndStandarddeviation(points.get("minusPerSelection"))); } return result; } private static Map<String, Map<String, List<Double>>> getPointsDataStructure(List<File> inputFiles) { Map<String, Map<String,List<Double>>> points=new HashMap<String, Map<String,List<Double>>>(); for(String s:new String[]{"abs","absPerDB","absPerSelection","square","squarePerDB","squarePerSelection","minus","minusPerDB","minusPerSelection"}){ points.put(s,new HashMap<String,List<Double>>()); } points.get("abs").put("",new ArrayList<Double>()); points.get("square").put("",new ArrayList<Double>()); points.get("minus").put("",new ArrayList<Double>()); for(File f:inputFiles){ String[] n=f.getName().substring(0,f.getName().lastIndexOf(".")).split("_"); points.get("absPerSelection").put(n[1],new ArrayList<Double>()); points.get("squarePerSelection").put(n[1],new ArrayList<Double>()); points.get("minusPerSelection").put(n[1],new ArrayList<Double>()); if(n.length==5){ points.get("absPerDB").put(n[4],new ArrayList<Double>()); points.get("squarePerDB").put(n[4],new ArrayList<Double>()); points.get("minusPerDB").put(n[4],new ArrayList<Double>()); }else{ points.get("absPerDB").put("",new ArrayList<Double>()); points.get("squarePerDB").put("",new ArrayList<Double>()); points.get("minusPerDB").put("",new ArrayList<Double>()); } } return points; } private static Map<String, TreeMap<Double, double[]>> getResultDataStructure( List<List<double[]>> r) { Map<String,TreeMap<Double, double[]>> result=new HashMap<String, TreeMap<Double, double[]>>(); for(String s:new String[]{"_square","_squarePerDB","_squarePerSelection","_abs","_absPerDB","_absPerSelection","_minus","_minusPerDB","_minusPerSelection"}){ TreeMap<Double, double[]> resultTmp=new TreeMap<Double, double[]>(); result.put(s, resultTmp); for(List<double[]> dl:r){ for(double[] d:dl){ resultTmp.put(d[0],new double[2]); } } } return result; } public static double[] getAverageAndStandarddeviation(List<Double> allPoints){ Map<String, List<Double>> tmp=new HashMap<String, List<Double>>(); tmp.put("", allPoints); return getAverageAndStandarddeviation(tmp); } public static double[] getAverageAndStandarddeviation(Map<String,List<Double>> allPoints){ double allAvg=0; double allS=0; for(List<Double> points:allPoints.values()){ double sum=0; for(double a:points){ sum+=a; } double avg=sum/points.size(); allAvg+=avg; double s=0; for(double a:points){ s+=Math.pow(a-avg,2); } s=Math.pow(s/(points.size()), 0.5); allS+=s; } return new double[]{allAvg/allPoints.size(), allS/allPoints.size()}; } public static double[] getAverageAndStandardDeviation(List<Double> points){ double[] result=new double[2]; double sum=0; for(double a:points){ sum+=a; } double avg=sum/points.size(); result[0]=avg; double s=0; for(double a:points){ s+=Math.pow(a-avg,2); } s=Math.pow(s/(points.size()), 0.5); result[1]=s; return result; } private static Map<String, TreeMap<Double, double[]>> getAverageDistancePerPosition(double minQValue, double maxQValue, List<File> inputFiles, boolean normalizedEstimated) throws Exception{ List<List<double[]>> r=getPoints(inputFiles, minQValue, maxQValue, true, true, "and", true, normalizedEstimated); int max=0; for(List<double[]> dl:r){ max=Math.max(max,dl.size()); } Map<String, TreeMap<Double, double[]>> result = getResultDataStructure(r); for(int i=0;i<max;i++){ Map<String, Map<String, List<Double>>> points = getPointsDataStructure(inputFiles); for(int k=0;k<inputFiles.size();k++){ List<double[]> dl=r.get(k); String[] n=inputFiles.get(k).getName().substring(0,inputFiles.get(k).getName().lastIndexOf(".")).split("_"); if(i<dl.size()){ double[] d=dl.get(i); double square=Math.pow(d[1]-d[0],2); double abs=Math.abs(d[1]-d[0]); double minus=d[1]-d[0]; points.get("minus").get("").add(minus); points.get("square").get("").add(square); points.get("abs").get("").add(abs); points.get("absPerSelection").get(n[1]).add(abs); points.get("squarePerSelection").get(n[1]).add(square); points.get("minusPerSelection").get(n[1]).add(minus); if(n.length==5){ points.get("absPerDB").get(n[4]).add(abs); points.get("squarePerDB").get(n[4]).add(square); points.get("minusPerDB").get(n[4]).add(minus); }else{ points.get("absPerDB").get("").add(abs); points.get("squarePerDB").get("").add(square); points.get("minusPerDB").get("").add(minus); } } } result.get("_square").put(1.0*i, getAverageAndStandarddeviation(points.get("square"))); result.get("_squarePerDB").put(1.0*i, getAverageAndStandarddeviation(points.get("squarePerDB"))); result.get("_squarePerSelection").put(1.0*i, getAverageAndStandarddeviation(points.get("squarePerSelection"))); result.get("_abs").put(1.0*i, getAverageAndStandarddeviation(points.get("abs"))); result.get("_absPerDB").put(1.0*i, getAverageAndStandarddeviation(points.get("absPerDB"))); result.get("_absPerSelection").put(1.0*i, getAverageAndStandarddeviation(points.get("absPerSelection"))); result.get("_minus").put(1.0*i, getAverageAndStandarddeviation(points.get("minus"))); result.get("_minusPerDB").put(1.0*i, getAverageAndStandarddeviation(points.get("minusPerDB"))); result.get("_minusPerSelection").put(1.0*i, getAverageAndStandarddeviation(points.get("minusPerSelection"))); } return result; } private static void getQValues(int numberSelections, File inputFile, File outputFile) throws Exception{ TreeMap<String, MassBank> massbankFilesOriginal=Utils.getAllDBFiles(originalDBFolders, ser, false, false); int repetitions=1; if(numberSelections>1)repetitions=2; Map<String,List<List<MassBank>>> selectionFinal=new HashMap<String, List<List<MassBank>>>(); for(int rep=0;rep<repetitions;rep++){ Map<String,Set<MassBank>> selectionTmp=new HashMap<String, Set<MassBank>>(); for(MassBank mb:massbankFilesOriginal.values()){ String v=mb.massbankID.replaceAll("\\d", ""); if(!selectionTmp.containsKey(v))selectionTmp.put(v, new HashSet<MassBank>()); selectionTmp.get(v).add(mb); } Random r=new Random(); Map<String,List<List<MassBank>>> selectionTmp2=new HashMap<String, List<List<MassBank>>>(); for(Entry<String, Set<MassBank>> e:selectionTmp.entrySet()){ List<List<MassBank>> tmp=new ArrayList<List<MassBank>>(); selectionTmp2.put(e.getKey(), tmp); for(int i=0;i<numberSelections;i++)tmp.add(new ArrayList<MassBank>()); List<MassBank> tmp2=new ArrayList<MassBank>(e.getValue()); int i=0; while(!tmp2.isEmpty()){ int next=r.nextInt(tmp2.size()); tmp.get(i%numberSelections).add(tmp2.get(next)); tmp2.remove(next); i++; } } Map<String,List<List<MassBank>>> selection=new HashMap<String, List<List<MassBank>>>(); for(Entry<String, List<List<MassBank>>> e:selectionTmp2.entrySet()){ List<List<MassBank>> tmp=new ArrayList<List<MassBank>>(); selection.put(e.getKey(), tmp); for(int i=0;i<e.getValue().size();i++)tmp.add(new ArrayList<MassBank>()); for(int i=0;i<e.getValue().size();i++){ for(int j=0;j<e.getValue().size();j++){ if(i!=j||numberSelections==1)tmp.get(i).addAll(e.getValue().get(j)); } } } for(Entry<String, List<List<MassBank>>> e:selection.entrySet()){ if(!selectionFinal.containsKey(e.getKey())){ selectionFinal.put(e.getKey(), e.getValue()); }else{ selectionFinal.get(e.getKey()).addAll(e.getValue()); } } } for (int i=0;i<querys.length;i++){ String queryLong=querys[i]; for(String s:decoyMethods){ if(s.equals("Original"))continue; for(String searchMethod:searchMethods){ for(String masses:new String[]{"HitStatistic_DifferentMassesExcluded_","HitStatistic_DMEHighFDR_"}){ File qValuesFile=new File(outputFile.getAbsolutePath()+sep+searchMethod); if (!qValuesFile.exists())qValuesFile.mkdirs(); File tmpFile2=new File(inputFile.getAbsolutePath()+sep+searchMethod+sep+queryLong+s); List<File> searchresultsFoldersDecoy = new ArrayList<File>(); if(tmpFile2.exists()){ for(File f:tmpFile2.listFiles()){ if(f.getName().startsWith(masses)&&(numberSelections==1||f.getName().endsWith("_1.txt")))searchresultsFoldersDecoy.add(f); } } File searchresultsFoldersOriginal = new File(inputFile.getAbsolutePath()+sep+searchMethod+sep+masses+queryLong+"Original.txt"); if(!searchresultsFoldersOriginal.exists())continue; if(s.equals("RandomDecoy")){ HitStatistic hsOriginal=new HitStatistic(searchresultsFoldersOriginal,massbankFilesOriginal); String v=hsOriginal.hits.get(0).massbankQuery.massbankID.replaceAll("\\d",""); for(int k=0;k<selectionFinal.get(v).size();k++){ List<MassBank> mb=selectionFinal.get(v).get(k); File file=new File(outputFile.getAbsolutePath()+sep+searchMethod+sep+masses+queryLong+s+sep+"QValues_Selection"+k+"_"+masses+queryLong+s+".qValue"); if(!file.getParentFile().exists())file.getParentFile().mkdir(); HitStatistic.writeQValuesDecoyHits(new File(outputFile.getAbsolutePath()+sep+"RandomDecoyValues"), file, hsOriginal, mb, false); } }else{ if(searchresultsFoldersDecoy==null||searchresultsFoldersDecoy.isEmpty())continue; for(File f:searchresultsFoldersDecoy){ // if(!f.getName().equals("HitStatistic_MPTreesOriginal-APTreesRandomPeaks_1.txt")||!searchMethod.equals("MassBank"))continue; System.out.print("getQValues: "+f.getAbsolutePath()+"..."); HitStatistic hsDecoy=new HitStatistic(f,massbankFilesOriginal); HitStatistic hsOriginal=new HitStatistic(searchresultsFoldersOriginal,massbankFilesOriginal); // HitStatistic.writeEstimatedQValueVSCalculatedQValueToFile(new File(statisticsFile.getAbsolutePath()+sep+"QValues_"+f.getName()), hsOriginal, hsDecoy, HitStatistic.HitMerge.Add, false, null); String v=hsOriginal.hits.get(0).massbankQuery.massbankID.replaceAll("\\d",""); for(int k=0;k<selectionFinal.get(v).size();k++){ List<MassBank> mb=selectionFinal.get(v).get(k); File folder=new File(qValuesFile.getAbsolutePath()+sep+f.getName().substring(0,f.getName().lastIndexOf("_"))); if(!folder.exists())folder.mkdir(); HitStatistic.writeEstimatedQValueVSCalculatedQValueToFile(new File(folder.getAbsolutePath()+sep+"QValues_Selection"+k+"_"+f.getName().replaceAll(".txt",".qValue")), new File(folder.getAbsolutePath()+sep+"QValues_Selection"+k+"_"+f.getName().replaceAll(".txt",".qValueMean")), new File(folder.getAbsolutePath()+sep+"QValues_Selection"+k+"_"+f.getName().replaceAll(".txt", ".hitlist")), hsOriginal, hsDecoy, HitStatistic.HitMerge.Add, false, mb); HitStatistic.writeEstimatedQValueVSCalculatedQValueToFile(new File(folder.getAbsolutePath()+sep+"QValues_Selection"+k+"_"+f.getName().replaceAll(".txt",".qValueMerge")), new File(folder.getAbsolutePath()+sep+"QValues_Selection"+k+"_"+f.getName().replaceAll(".txt",".qValueMergeMean")), new File(folder.getAbsolutePath()+sep+"QValues_Selection"+k+"_"+f.getName().replaceAll(".txt", ".hitlistMerge")), hsOriginal, hsDecoy, HitStatistic.HitMerge.Merge, false, mb); //System.out.println("Selection "+k+" done."); } System.out.println("done"); } } } } } } } private static void statisticsOriginal(File inputFile, File outputFile, File outputFileChanges, File graphicsFolder) throws IOException, Exception { BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); bw.write("\t"); bw.write("\t"); bw.write(HitStatistic.getHeaderString()); bw.write("\t\t"); bw.write(HitStatistic.getHeaderString()); bw.write("\tat least one hit"); bw.newLine(); TreeMap<String, MassBank> massbankFilesOriginal=Utils.getAllDBFiles(originalDBFolders, ser, false, false); TreeMap<String, Map<MassBank, HitDescription>> stats=new TreeMap<String, Map<MassBank, HitDescription>>(); for (int i=0;i<querys.length;i++){ TreeMap<String, Map<MassBank, HitDescription>> statsTmp=new TreeMap<String, Map<MassBank, HitDescription>>(); TreeMap<String, HitStatistic> allHitstatistics=new TreeMap<String, HitStatistic>(); TreeMap<String, HitStatistic> allHitstatisticsDifferentMassesExcluded=new TreeMap<String, HitStatistic>(); String queryLong=querys[i]; String decoy="Original"; System.out.println("statisticsOriginal: "+queryLong+decoy); bw.write(queryLong+decoy);bw.newLine(); for(String searchMethod:searchMethodsStatisticsOriginal){ File hitstatistics = new File(inputFile.getAbsolutePath()+sep+searchMethod+sep+"HitStatistic_"+queryLong+decoy+".txt"); File hitstatisticsDifferentMassesExcluded = new File(inputFile.getAbsolutePath()+sep+searchMethod+sep+"HitStatistic_DifferentMassesExcluded_"+queryLong+decoy+".txt"); if(hitstatistics.exists()&&hitstatisticsDifferentMassesExcluded.exists()){ HitStatistic hits=new HitStatistic(hitstatistics, massbankFilesOriginal); bw.write(searchMethod+"\tall\t"); bw.write(hits.toEntryString()); Map<MassBank, HitDescription> stat=hits.getHitDescription(); stats.put(queryLong+decoy+"-"+searchMethod, stat); allHitstatistics.put(queryLong+decoy+"-"+searchMethod, hits); hits=new HitStatistic(hitstatisticsDifferentMassesExcluded, massbankFilesOriginal); bw.write("\tdifferent masses excluded:\t"); bw.write(hits.toEntryString()); bw.write("\t"+hits.getNumberEntriesWithAtLeastOneHit()); stat=hits.getHitDescription(); statsTmp.put(queryLong+decoy+"-"+searchMethod+"-SameMass", stat); allHitstatisticsDifferentMassesExcluded.put(queryLong+decoy+"-"+searchMethod+"-SameMass", hits); bw.newLine(); } bw.flush(); } HitStatistic.writeROCCurves(new File(graphicsFolder.getAbsolutePath()+sep+"ROCCurve_"+queryLong+decoy+".jpg"), allHitstatistics); HitStatistic.writeROCCurves(new File(graphicsFolder.getAbsolutePath()+sep+"ROCCurve_DifferentMassesExcluded_"+queryLong+decoy+".jpg"), allHitstatisticsDifferentMassesExcluded); stats.putAll(statsTmp); } bw.close(); compareSearchMethods(outputFileChanges, stats); } private static void statisticsHighFDR(File inputFile, File outputFile, File outputFileChanges, File graphicsFolder) throws IOException, Exception { BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); bw.write("\t\t"); bw.write(HitStatistic.getHeaderString()); bw.write("\tat least one hit"); bw.newLine(); TreeMap<String, MassBank> massbankFilesOriginal=Utils.getAllDBFiles(originalDBFolders, ser, false, false); TreeMap<String, Map<MassBank, HitDescription>> stats=new TreeMap<String, Map<MassBank, HitDescription>>(); for (int i=0;i<querys.length;i++){ TreeMap<String, Map<MassBank, HitDescription>> statsTmp=new TreeMap<String, Map<MassBank, HitDescription>>(); TreeMap<String, HitStatistic> allHitstatisticsDifferentMassesExcluded=new TreeMap<String, HitStatistic>(); String queryLong=querys[i]; String decoy="Original"; System.out.println("statisticsOriginal: "+queryLong+decoy); bw.write(queryLong+decoy);bw.newLine(); for(String searchMethod:searchMethodsStatisticsOriginal){ File hitstatisticsDifferentMassesExcluded = new File(inputFile.getAbsolutePath()+sep+searchMethod+sep+"HitStatistic_DMEHighFDR_"+queryLong+decoy+".txt"); if(hitstatisticsDifferentMassesExcluded.exists()){ HitStatistic hits=new HitStatistic(hitstatisticsDifferentMassesExcluded, massbankFilesOriginal); bw.write("searchMethod\tdifferent masses excluded:\t"); bw.write(hits.toEntryString()); bw.write("\t"+hits.getNumberEntriesWithAtLeastOneHit()); Map<MassBank, HitDescription> stat=hits.getHitDescription(); statsTmp.put(queryLong+decoy+"-"+searchMethod+"-SameMass", stat); allHitstatisticsDifferentMassesExcluded.put(queryLong+decoy+"-"+searchMethod+"-SameMass", hits); bw.newLine(); } bw.flush(); } HitStatistic.writeROCCurves(new File(graphicsFolder.getAbsolutePath()+sep+"ROCCurve_DMEHighFDR_"+queryLong+decoy+".jpg"), allHitstatisticsDifferentMassesExcluded); stats.putAll(statsTmp); } bw.close(); compareSearchMethods(outputFileChanges, stats); } private static void compareSearchMethods(File outputFileChanges, TreeMap<String, Map<MassBank, HitDescription>> stats) throws IOException { TreeMap<String, Map<String, HitDescription>> tmp=new TreeMap<String, Map<String, HitDescription>>(); for(Entry<String, Map<MassBank, HitDescription>> e:stats.entrySet()){ if(!tmp.containsKey(e.getKey()))tmp.put(e.getKey(), new TreeMap<String, HitDescription>()); Map<String, HitDescription> tmp2=tmp.get(e.getKey()); for(Entry<MassBank, HitDescription> e2:e.getValue().entrySet()){ tmp2.put(SimilarityMatrix.getIDDatasetCharge(e2.getKey().massbankID), e2.getValue()); } } Map<String, int[][]> countsDetails=new TreeMap<String,int[][]>(); List<String> allQueries=new ArrayList<String>(); allQueries.addAll(tmp.keySet()); for(int i=0;i<allQueries.size();i++){ for(int j=0;j<allQueries.size();j++){ Map<String, HitDescription> stat1=tmp.get(allQueries.get(i)); Map<String, HitDescription> stat2=tmp.get(allQueries.get(j)); Set<String> allIDs=new HashSet<String>(); allIDs.addAll(stat1.keySet()); allIDs.addAll(stat2.keySet()); for(String id:allIDs){ HitDescription hd1=stat1.get(id); HitDescription hd2=stat2.get(id); if(hd1==null)hd1=HitDescription.NotInQuery; if(hd2==null)hd2=HitDescription.NotInQuery; Integer c=HitStatistic.compareHitDescription(hd1, hd2); String countsQualityKey="_x"; if(c!=null){ if(c==0)countsQualityKey="_equal"; else if(c<0)countsQualityKey="_better"; else if(c>0)countsQualityKey="_worse"; } if(!countsDetails.containsKey(countsQualityKey))countsDetails.put(countsQualityKey, new int[allQueries.size()][allQueries.size()]); countsDetails.get(countsQualityKey)[i][j]++; String s1=HitStatistic.getHitDescriptionString(hd1); String s2=HitStatistic.getHitDescriptionString(hd2); String countsDetailsKey=s1+"->"+s2; if(!countsDetails.containsKey(countsDetailsKey))countsDetails.put(countsDetailsKey, new int[allQueries.size()][allQueries.size()]); countsDetails.get(countsDetailsKey)[i][j]++; } } } BufferedWriter bw2=new BufferedWriter(new FileWriter(outputFileChanges)); List<String> keys=new ArrayList<String>(); keys.addAll(countsDetails.keySet()); for (String k:keys)bw2.write("\t"+k); bw2.newLine(); for(int i=0;i<allQueries.size();i++){ for(int j=0;j<allQueries.size();j++){ String[] query1=allQueries.get(i).split("-"); String[] query2=allQueries.get(j).split("-"); int diff=0; for(int z=0;z<Math.min(query1.length, query2.length);z++){ if(!query1[z].equals(query2[z]))diff++; } diff+=Math.abs(query1.length-query2.length); if(diff!=1)continue; bw2.write(allQueries.get(i)+" vs. "+allQueries.get(j)); for(String k:keys){ int[][] c=countsDetails.get(k); bw2.write("\t"+c[i][j]); } bw2.newLine(); } } bw2.close(); } private static void getHitLists(File searchResultsFolder, File statisticsFolder) throws IOException, Exception { TreeMap<String, MassBank> massbankFilesOriginal=Utils.getAllDBFiles(originalDBFolders, ser, false, false); Map<String, Map<MassBank, List<MassBank>>> exclusions70= new HashMap<String, Map<MassBank, List<MassBank>>>(); for (int i=0;i<querys.length;i++){ String queryLong=querys[i]; for(String s:decoyMethods){ for(String searchMethod:searchMethodsStatisticsOriginal){ File statisticsFile=new File(statisticsFolder.getAbsolutePath()+sep+searchMethod); if (!statisticsFile.exists())statisticsFile.mkdir(); String ending=(searchMethod.equals("DBSearch")?".txt":".csv"); File files=new File(searchResultsFolder.getAbsolutePath()+sep+searchMethod+sep+"pos"+sep+queryLong+s+ending); boolean isDirectory=!files.exists(); List<File> searchresultsFoldersDecoy = getSearchResultsFiles(files); if(searchresultsFoldersDecoy.isEmpty())continue; for(File f:searchresultsFoldersDecoy){ SimilarityMatrix mDecoy=new SimilarityMatrix(f, massbankFilesOriginal); String name=f.getName(); if(name.endsWith(".csv"))name=name.replaceAll(".csv",".txt"); File tmp=new File(statisticsFile.getAbsolutePath()+sep+(isDirectory?f.getParentFile().getName():"")); if(!tmp.exists())tmp.mkdir(); System.out.println("getHitLists: " + tmp.getAbsolutePath()+sep+"HitStatistic_"+name); HitStatistic hits=null; mDecoy.clearExclusionList(); hits=mDecoy.getHitStatistic(); hits.writeHitStatisticToFile(new File(tmp.getAbsolutePath()+sep+"HitStatistic_"+name)); String[] split=queryLong.split("-"); boolean isTrees=false; if(split[0].contains("Trees")&&split[1].contains("Trees"))isTrees=true; mDecoy.clearExclusionList(); if(isTrees){ mDecoy.excludeDifferentFormulas(); }else{ mDecoy.excludeDifferentMass(ppm, ae); } hits=mDecoy.getHitStatistic(); hits.writeHitStatisticToFile(new File(tmp.getAbsolutePath()+sep+"HitStatistic_DifferentMassesExcluded_"+name)); String data=queryLong; if(!exclusions70.containsKey(data))exclusions70.put(data, getExclusions(0.5,mDecoy)); mDecoy.excludeMassBanksFromDB(exclusions70.get(data)); hits=mDecoy.getHitStatistic(); hits.writeHitStatisticToFile(new File(tmp.getAbsolutePath()+sep+"HitStatistic_DMEHighFDR_"+name)); } } } } } private static Map<MassBank, List<MassBank>> getExclusions(double percentage, SimilarityMatrix mDecoy) { System.out.println("getExclusionList"); System.out.println("methods DB"); for(String s:mDecoy.methodsDB){ // System.out.print(s); } System.out.println(); System.out.println("methods query"); for(String s:mDecoy.methodsQuery){ // System.out.print(s); } System.out.println(); Map<MassBank, List<MassBank>> result=new HashMap<MassBank, List<MassBank>>(); Map<MassBank, List<MassBank>> hitsTP=new HashMap<MassBank, List<MassBank>>(); Map<MassBank, List<MassBank>> hitsFP=new HashMap<MassBank, List<MassBank>>(); for(int i=0;i<mDecoy.massbankQuery.size();i++){ hitsTP.put(mDecoy.massbankQuery.get(i),new ArrayList<MassBank>()); hitsFP.put(mDecoy.massbankQuery.get(i),new ArrayList<MassBank>()); for(int j=0;j<mDecoy.massbankDB.size();j++){ boolean isEntry=!Double.isNaN(mDecoy.getSimilarityValue(i, j)); boolean isSameInchi=mDecoy.massbankQuery.get(i).hasEqualInChiKey(mDecoy.massbankDB.get(j)); if(isEntry){ if(isSameInchi)hitsTP.get(mDecoy.massbankQuery.get(i)).add(mDecoy.massbankDB.get(j)); else hitsFP.get(mDecoy.massbankQuery.get(i)).add(mDecoy.massbankDB.get(j)); } } } List<MassBank> onlyTP=new ArrayList<MassBank>(); List<MassBank> onlyFP=new ArrayList<MassBank>(); List<MassBank> both=new ArrayList<MassBank>(); List<MassBank> none=new ArrayList<MassBank>(); for(int i=0;i<mDecoy.massbankQuery.size();i++){ int numberTP=hitsTP.get(mDecoy.massbankQuery.get(i)).size(); int numberFP=hitsFP.get(mDecoy.massbankQuery.get(i)).size(); if(numberTP==0&&numberFP==0)none.add(mDecoy.massbankQuery.get(i)); if(numberTP!=0&&numberFP==0)onlyTP.add(mDecoy.massbankQuery.get(i)); if(numberTP==0&&numberFP!=0)onlyFP.add(mDecoy.massbankQuery.get(i)); if(numberTP!=0&&numberFP!=0)both.add(mDecoy.massbankQuery.get(i)); } System.out.println("number only TP: "+ onlyTP.size()); System.out.println("number only FP: "+ onlyFP.size()); System.out.println("number both: "+ both.size()); System.out.println("number none: "+ none.size()); double currentFDR=1.0*onlyFP.size()/(onlyFP.size()+onlyTP.size()+both.size()); System.out.println("current number FDR: "+ currentFDR); int numberDeletionsBoth=(int)Math.ceil(percentage*(onlyFP.size()+onlyTP.size()+both.size())-onlyFP.size()); System.out.println("number deletions in both recommended: "+numberDeletionsBoth); numberDeletionsBoth=Math.min(numberDeletionsBoth, both.size()); System.out.println("number deletions in both possible: "+numberDeletionsBoth); Random random=new Random(); // for(int i=0;i<numberDeletionsBoth;i++){ // int r=random.nextInt(both.size()); // MassBank mb=both.get(r); // result.put(mb, hitsTP.get(mb)); // both.remove(mb); // onlyFP.add(mb); // } currentFDR=1.0*onlyFP.size()/(onlyFP.size()+onlyTP.size()+both.size()); System.out.println("number only TP after deletions: "+ onlyTP.size()); System.out.println("number only FP after deletions: "+ onlyFP.size()); System.out.println("number both after deletions: "+ both.size()); System.out.println("number none after deletions: "+ none.size()); System.out.println("FDR after deletions: "+ currentFDR); if(currentFDR<percentage){ double numberDeletionsTP=(int)Math.ceil(onlyTP.size()-(onlyFP.size()-percentage*(onlyFP.size()+both.size()))/percentage); System.out.println("number deletions in TPs: "+ numberDeletionsTP); for(int i=0;i<numberDeletionsTP;i++){ if(onlyTP.size()==0)break; int r=random.nextInt(onlyTP.size()); MassBank mb=onlyTP.get(r); result.put(mb, hitsTP.get(mb)); onlyTP.remove(mb); none.add(mb); } } System.out.println("number only TP: "+ onlyTP.size()); System.out.println("number only FP: "+ onlyFP.size()); System.out.println("number both: "+ both.size()); System.out.println("number none: "+ none.size()); currentFDR=1.0*onlyFP.size()/(onlyFP.size()+onlyTP.size()+both.size()); System.out.println("current number FDR: "+ currentFDR); return result; } private static void getRankStatistic(File searchResultsFolder, File graphicsFolder) throws IOException, Exception { TreeMap<String, MassBank> massbankFilesOriginal=Utils.getAllDBFiles(originalDBFolders, ser, false, false); for (int i=0;i<querys.length;i++){ String queryLong=querys[i]; for(String searchMethod:searchMethods){ Map<String, Map<DatabaseType, Double>[]> result=new HashMap<String, Map<DatabaseType, Double>[]>(); Map<String, Map<DatabaseType, Double>[]> resultDifferentMassesExcluded=new HashMap<String, Map<DatabaseType, Double>[]>(); for(String s:decoyMethods){ if(s.equals("Original"))continue; File graphicsFile=new File(graphicsFolder.getAbsolutePath()+sep+searchMethod); if (!graphicsFile.exists())graphicsFile.mkdirs(); String ending=(searchMethod.equals("DBSearch")?".txt":".csv"); File original=new File(searchResultsFolder.getAbsolutePath()+sep+searchMethod+sep+"pos"+sep+queryLong+"Original"+ending); if(!original.exists())continue; SimilarityMatrix mOriginal=new SimilarityMatrix(original, massbankFilesOriginal); File files=new File(searchResultsFolder.getAbsolutePath()+sep+searchMethod+sep+"pos"+sep+queryLong+s+ending); List<File> searchresultsFoldersDecoy = getSearchResultsFiles(files); if(searchresultsFoldersDecoy.isEmpty())continue; List<SimilarityMatrix> mDecoys=new ArrayList<SimilarityMatrix>(); for(File f:searchresultsFoldersDecoy){ mDecoys.add(new SimilarityMatrix(f, massbankFilesOriginal)); } String name=files.getName()+".jpg"; name=name.replaceAll(".csv","").replaceAll(".txt",""); System.out.println("getRankStatistics: " + graphicsFile.getAbsolutePath()+sep+"Hitstatistics_RankDistribution_"+name); // for(SimilarityMatrix mDecoy:mDecoys)mDecoy.excludeSameInChi(); // mOriginal.excludeSameInChi(); Map<DatabaseType, Double>[] r=SimilarityMatrix.getRankDistribution(new File(graphicsFile.getAbsolutePath()+sep+"Hitstatistics_RankDistribution_"+name), mOriginal, mDecoys,20); result.put(name.replaceAll(".jpg", ""), r); System.out.println("getRankStatistics: " + graphicsFile.getAbsolutePath()+sep+"Hitstatistics_DifferentMassesExcluded_RankDistribution_"+name); String[] split=queryLong.split("-"); boolean isTrees=false; if(split[0].contains("Trees")&&split[1].contains("Trees"))isTrees=true; if(isTrees){ for(SimilarityMatrix mDecoy:mDecoys)mDecoy.excludeDifferentFormulas(); mOriginal.excludeDifferentFormulas(); }else{ for(SimilarityMatrix mDecoy:mDecoys)mDecoy.excludeDifferentMass(ppm, ae); mOriginal.excludeDifferentMass(ppm, ae); } r=SimilarityMatrix.getRankDistribution(new File(graphicsFile.getAbsolutePath()+sep+"Hitstatistics_DifferentMassesExcluded_RankDistribution_"+name), mOriginal, mDecoys, 20); resultDifferentMassesExcluded.put(name.replaceAll(".jpg", ""), r); System.out.println(); } for(Map<String, Map<DatabaseType, Double>[]> res:new Map[]{result, resultDifferentMassesExcluded}){ String add=""; if(res==resultDifferentMassesExcluded)add="DifferentMassesExcluded_"; File outputFile=new File(graphicsFolder.getAbsolutePath()+sep+searchMethod+sep+"Hitstatistics_"+add+"RankDistribution_"+queryLong+".jpg"); if(!outputFile.getParentFile().exists())outputFile.getParentFile().mkdirs(); final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for(Entry<String, Map<DatabaseType, Double>[]> e:res.entrySet()){ for(int j=0;j<e.getValue().length;j++){ double decoy=0.0; double original=0.0; if(e.getValue()[j].containsKey(DatabaseType.Decoy))decoy=e.getValue()[j].get(DatabaseType.Decoy); if(e.getValue()[j].containsKey(DatabaseType.Original))original=e.getValue()[j].get(DatabaseType.Original); if(decoy!=0.0||original!=0.0)dataset.addValue(decoy/(decoy+original)-0.5,e.getKey(),Integer.toString(j)); } } final JFreeChart chart = ChartFactory.createBarChart("Boxplot","Ranks","Percentage",dataset); ChartUtilities.saveChartAsJPEG(outputFile, chart, Math.min(2000,20*100), 1000); } System.out.println(); } } } private static void checkEquality(File searchResultsFolder, File graphicsFolder) throws IOException, Exception { TreeMap<String, MassBank> massbankFilesOriginal=Utils.getAllDBFiles(originalDBFolders, ser, false, false); // for(String searchMethod:searchMethods){ for(String searchMethod:new String[]{"Equality"}){ for(String s:decoyMethods){ if(s.equals("Original"))continue; File graphicsFile=new File(graphicsFolder.getAbsolutePath()+sep+searchMethod); if (!graphicsFile.exists())graphicsFile.mkdirs(); File outputFile=new File(graphicsFile.getAbsolutePath()+sep+"EuqalityCheck_"+s+".txt"); BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); for (int i=0;i<querys.length;i++){ String queryLong=querys[i]; String[] starts=new String[]{"AP","MP","BP","OP","QP","GP"}; for(String ending:starts){ if(queryLong.contains(ending)){ queryLong=ending+queryLong.substring(2); } } String ending=(searchMethod.equals("DBSearch")?".txt":".csv"); // File original=new File(searchResultsFolder.getAbsolutePath()+sep+searchMethod+sep+"pos"+sep+queryLong+"Original"+ending); // if(!original.exists())continue; // SimilarityMatrix mOriginal=new SimilarityMatrix(original, massbankFilesOriginal); File files=new File(searchResultsFolder.getAbsolutePath()+sep+searchMethod+sep+"pos"+sep+queryLong+s+ending); List<File> searchresultsFoldersDecoy = getSearchResultsFiles(files); if(searchresultsFoldersDecoy.isEmpty())continue; for(File f:searchresultsFoldersDecoy){ bw.write(f.getAbsolutePath()+": "); int numberEqual=0; String which="("; SimilarityMatrix m=new SimilarityMatrix(f, massbankFilesOriginal); for(int l=0;l<m.similarity.length;l++){ for(int n=0;n<m.similarity[l].length;n++){ if(m.similarity[l][n]!=0){ numberEqual++; which+=m.massbankQuery.get(l).massbankID+"-"+m.massbankDB.get(n).massbankID+" "; } } } which+=")"; bw.write(Double.toString(numberEqual)+" "+which); bw.newLine(); } String name=files.getName(); name=name.replaceAll(".csv","").replaceAll(".txt",""); System.out.println("checkEquality: " + s+" "+name+".txt"); bw.newLine(); } bw.close(); } } } private static List<File> getSearchResultsFiles(File files) { List<File> searchresultsFoldersDecoy = new ArrayList<File>(); if(files.exists()){ searchresultsFoldersDecoy.add(files); }else{ File allFiles=new File(files.getAbsolutePath().substring(0,files.getAbsolutePath().lastIndexOf("."))); if(allFiles.exists()&&allFiles.isDirectory()){ for(File inFile:allFiles.listFiles()){ searchresultsFoldersDecoy.add(inFile); } } } return searchresultsFoldersDecoy; } } class FileExtensionFilter implements FilenameFilter { private Set<String> exts = new HashSet<String>(); /** * @param extensions * a list of allowed extensions, without the dot, e.g. * <code>"xml","html","rss"</code> */ public FileExtensionFilter(String... extensions) { for (String ext : extensions) { exts.add("." + ext.toLowerCase().trim()); } } public boolean accept(File dir, String name) { final Iterator<String> extList = exts.iterator(); while (extList.hasNext()) { if (name.toLowerCase().endsWith(extList.next())) { return true; } } return false; } }
73,681
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
Query.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/Query.java
package de.unijena.bioinf.statistics; import de.unijena.bioinf.decoy.model.MassBank; public class Query{ String queryID; MassBank massbank; // public Query(String[] line){ // queryID=line[1]; // } public Query(String queryID){ this.queryID=queryID; } public Query(Query q){ this.queryID=q.queryID; this.massbank=q.massbank; } public String getDB(){ return queryID.replaceAll("\\d",""); } public String getNumber(){ return queryID.replaceAll("\\D",""); } public String getDataset(){ return queryID.substring(0,1); } }
594
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MainOld.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/MainOld.java
package de.unijena.bioinf.statistics; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import de.unijena.bioinf.decoy.model.MassBank; public class MainOld { static String searchMethod="MassBank"; // static File dbFolder=new File("U:\\MSBlast\\DB"); static File statisticsFolder=new File("U:\\MSBlast\\statisticsOld\\"+searchMethod); static String addOutputFile="Pooled"; static String addOriginal=""; static String sepOriginal="."; static String fileEndingOriginal="csv"; static String addDecoy=""; static String sepDecoy=""; static String fileEndingDecoy=""; static int numberOfDatabases=1; public static void main(String args[]) throws Exception{ File[] inputFilesOriginal=new File[]{ new File("U:\\MSBlast\\searchResults\\"+searchMethod+"\\pos\\MPOriginal-APOriginal"+addOriginal+sepOriginal+fileEndingOriginal) }; File[] inputFilesDecoy=new File[]{ // new File("U:\\MSBlast\\searchResults\\"+searchMethod+"\\pos\\MPOriginal-APConditionalPeaks"+addDecoy+sepDecoy+fileEndingDecoy), // new File("U:\\MSBlast\\searchResults\\"+searchMethod+"\\pos\\MPOriginal-APRandomPeaks"+addDecoy+sepDecoy+fileEndingDecoy), new File("U:\\MSBlast\\searchResults\\"+searchMethod+"\\pos\\MPOriginal-APReroot"+addDecoy+sepDecoy+fileEndingDecoy) }; File[] comparisonFiles=new File[inputFilesOriginal.length+inputFilesDecoy.length]; int k=0; for(File f:inputFilesOriginal){ if(f.isDirectory()){ comparisonFiles[k++]=f.listFiles()[0]; }else{ comparisonFiles[k++]=f; } } for(File f:inputFilesDecoy){ if(f.isDirectory()){ comparisonFiles[k++]=f.listFiles()[0]; }else{ comparisonFiles[k++]=f; } } Map<String, MassBank> dbFilesOriginal=getAllDBFiles(comparisonFiles); List<ResultList>[] resultsOriginal=new List[inputFilesOriginal.length]; for(int i=0;i<inputFilesOriginal.length;i++){ File f=inputFilesOriginal[i]; resultsOriginal[i]=ResultList.getResults(f, dbFilesOriginal); } List<List<ResultList>>[] resultsDecoy=new List[inputFilesDecoy.length]; for(int i=0;i<inputFilesDecoy.length;i++){ File folder=inputFilesDecoy[i]; resultsDecoy[i]=new ArrayList<List<ResultList>>(); if(folder.isDirectory()){ List<File> files=Arrays.asList(folder.listFiles()); Collections.sort(files); files=files.subList(0, Math.min(numberOfDatabases,files.size())); for(File f:files){ // resultsDecoy[i].add(ResultList.getResults(f, dbFilesOriginal)); if(resultsDecoy[i].size()==0){ resultsDecoy[i].add(ResultList.getResults(f, dbFilesOriginal)); }else{ resultsDecoy[i].get(0).addAll(ResultList.getResults(f, dbFilesOriginal)); } } }else{ resultsDecoy[i].add(ResultList.getResults(folder, dbFilesOriginal)); } } List<List<ResultList>>[] resultsAll=new List[resultsOriginal.length+resultsDecoy.length]; int i=0; for(List<ResultList> r:resultsOriginal){ List<List<ResultList>> tmp=new ArrayList<List<ResultList>>(); tmp.add(r); resultsAll[i++]=tmp; } for(List<List<ResultList>> r:resultsDecoy)resultsAll[i++]=r; if(!statisticsFolder.exists())statisticsFolder.mkdirs(); Plot.writeScoreDistributionOfTopRank(statisticsFolder, addOutputFile, resultsAll, 0.05); Plot.writeEstimatedQValueVSCalculatedQValue(statisticsFolder, addOutputFile, resultsOriginal, resultsDecoy); Plot.writeRankVSScore(statisticsFolder, addOutputFile, resultsAll, 10); Plot.writeRankVSPercentage(statisticsFolder, addOutputFile, resultsOriginal, resultsDecoy, 10); Plot.writeRankVSPercentage(statisticsFolder, addOutputFile+"OnlyDifferentInchi", getFilteredResultListsByInchi(resultsOriginal, false), getFilteredResultListsByInchi(resultsDecoy, false), 10); Plot.writeEstimatedQValueVSCalculatedQValue(statisticsFolder, addOutputFile+"OnlySameMass", getFilteredResultListsByMass(resultsOriginal, true), getFilteredResultListsByMass(resultsDecoy, true)); } public static List[] getFilteredResultListsByInchi(List[] results, boolean retainSame){ List[] result=new ArrayList[results.length]; for(int i=0;i<results.length;i++){ for(Object rl:results[i]){ if(rl.getClass().equals(ResultList.class)){ if(result[i]==null)result[i]=new ArrayList<ResultList>(); ResultList newRL=new ResultList((ResultList)rl); newRL.filterResultsByInChi(retainSame); if(!newRL.results.isEmpty())result[i].add(newRL); }else{ if(result[i]==null)result[i]=new ArrayList<List<ResultList>>(); List<ResultList> tmp=new ArrayList<ResultList>(); for(ResultList rl2:(List<ResultList>) rl){ ResultList newRL=new ResultList(rl2); newRL.filterResultsByInChi(retainSame); if(!newRL.results.isEmpty())tmp.add(newRL); } result[i].add(tmp); } } } return result; } public static List[] getFilteredResultListsByMass(List[] results, boolean retainSame){ List[] result=new ArrayList[results.length]; for(int i=0;i<results.length;i++){ for(Object rl:results[i]){ if(rl.getClass().equals(ResultList.class)){ if(result[i]==null)result[i]=new ArrayList<ResultList>(); ResultList newRL=new ResultList((ResultList)rl); newRL.filterResultsByMass(retainSame,20,5); if(!newRL.results.isEmpty())result[i].add(newRL); }else{ if(result[i]==null)result[i]=new ArrayList<List<ResultList>>(); List<ResultList> tmp=new ArrayList<ResultList>(); for(ResultList rl2:(List<ResultList>) rl){ ResultList newRL=new ResultList(rl2); newRL.filterResultsByMass(retainSame,20,5); if(!newRL.results.isEmpty())tmp.add(newRL); } result[i].add(tmp); } } } return result; } private static Map<String, MassBank> getAllDBFiles(File[] inputFiles)throws Exception { Map<String, MassBank> dbFiles=new HashMap<String,MassBank>(); Set<File> dbFolders=new HashSet<File>(); dbFolders.addAll(getFolders(inputFiles,"Query")); dbFolders.addAll(getFolders(inputFiles,"DB")); getAllDBFiles(dbFolders, dbFiles); return dbFiles; } public static Set<File> getFolders(File[] inputFiles,String queryOrDB) throws Exception{ Set<File> result=new HashSet<File>(); for(File f:inputFiles)result.addAll(getFolders(f,queryOrDB)); return result; } public static Set<File> getFolders(File inputFile, String queryOrDB) throws Exception{ BufferedReader br=new BufferedReader(new FileReader(inputFile)); String line; while((line=br.readLine())!=null){ if(line.startsWith(queryOrDB)){ Set<File> result=new HashSet<File>(); String[] queryFiles=line.substring(queryOrDB.length()+2).split(";"); for(String f:queryFiles)result.add(new File(f)); return result; } } return null; } public static void getAllDBFiles(Set<File> dbFolders, Map<String, MassBank> results) throws Exception{ for(File dbFolder:dbFolders)getAllDBFiles(dbFolder, results); } public static void getAllDBFiles(File dbFolder, Map<String, MassBank> results) throws Exception{ for(File f:dbFolder.listFiles()){ if(f.isFile()&&f.getName().endsWith(".txt")){ results.put(f.getName().replaceAll(".txt",""), new MassBank(f)); System.out.println(f.getAbsolutePath()); }else if (f.isDirectory()){ getAllDBFiles(f,results); } } } }
7,669
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
Plot.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/Plot.java
package de.unijena.bioinf.statistics; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.statistics.DefaultBoxAndWhiskerCategoryDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import de.unijena.bioinf.decoy.model.MassBank; public class Plot { public static void writeRankVSScore(File outputFile, String add, List<List<ResultList>>[] results, int length) throws Exception{ Set<String>[] legendQuery=new Set[results.length]; Set<String>[] legendDB=new Set[results.length]; String name="RankVSscore"; boolean isMean=false; for(int i=0;i<results.length;i++){ if(results[i].size()>1)isMean=true; if(legendQuery[i]==null)legendQuery[i]=new HashSet<String>(); if(legendDB[i]==null)legendDB[i]=new HashSet<String>(); List<ResultList> resultLists=results[i].get(0); for(ResultList resultList:resultLists){ legendQuery[i].add(resultList.query.getDB()); for(Result r:resultList.results)legendDB[i].add(r.getDB()); } } if(isMean)name+="Mean"; String[] legend=new String[results.length]; for(int i=0;i<legendQuery.length;i++){ String tmp=""; for(String s:legendQuery[i])tmp+=s+"_"; tmp=tmp.substring(0,tmp.length()-1); tmp+="-"; for(String s:legendDB[i])tmp+=s+"_"; tmp=tmp.substring(0,tmp.length()-1); legend[i]=tmp; } final DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset(); for (int i = 0; i < length; i++) { for (int j = 0; j < results.length; j++) { List<Double> scoreList=new ArrayList<Double>(); for(List<ResultList> rls:results[j]){ for(ResultList rl:rls){ if(i<rl.results.size())scoreList.add(rl.results.get(i).score); } } dataset.add(scoreList, legend[j], i); } } String fileName=""; for(String s:legend)fileName+=(s+"---"); fileName=fileName.substring(0,fileName.length()-3); JFreeChart chart=ChartFactory.createBoxAndWhiskerChart("Whiskerplot", "Ranks", "Scores", dataset, true); ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+"\\"+name+"_"+fileName+add+".jpg"), chart, Math.min(2000,length*100), 1000); } public static void writeScoreDistributionOfTopRank(File outputFile, String add, List<List<ResultList>>[] resultLists, double step) throws Exception{ for(List<List<ResultList>> resultList:resultLists){ Map<Double, Integer> topScoringMatchesAll=new TreeMap<Double,Integer>(); Map<Double, Integer> topScoringMatchesTrue=new TreeMap<Double,Integer>(); Map<Double, Integer> topScoringMatchesFalse=new TreeMap<Double,Integer>(); int numberTrueMatches=0; int numberFalseMatches=0; String fileName=null; String name="ScoreDistributionTopRank"; if(resultList.size()>1)name+="Mean"; for(List<ResultList> result:resultList){ if(fileName==null){ for(ResultList rl:result){ if(!rl.results.isEmpty())fileName=rl.query.getDB()+"-"+rl.results.get(0).getDB(); } } for(ResultList rl:result){ Collections.sort(rl.results); if(!rl.results.isEmpty()&&rl.results.get(0).massbank.inchi!=null&&rl.query.massbank.inchi!=null){ double value=Math.round(rl.results.get(0).score/step)*step; if(!topScoringMatchesAll.containsKey(value))topScoringMatchesAll.put(value, 0); topScoringMatchesAll.put(value,topScoringMatchesAll.get(value)+1); if(rl.results.get(0).massbank.inchi.equals(rl.query.massbank.inchi)){ if(!topScoringMatchesTrue.containsKey(value))topScoringMatchesTrue.put(value, 0); topScoringMatchesTrue.put(value,topScoringMatchesTrue.get(value)+1); numberTrueMatches++; }else{ if(!topScoringMatchesFalse.containsKey(value))topScoringMatchesFalse.put(value, 0); topScoringMatchesFalse.put(value,topScoringMatchesFalse.get(value)+1); numberFalseMatches++; } } } } XYSeries seriesTrue = new XYSeries("True Hits ("+numberTrueMatches+")"); for(Entry<Double,Integer> m:topScoringMatchesTrue.entrySet()){ seriesTrue.add(m.getKey(),new Double(1.0*m.getValue()/numberTrueMatches)); } XYSeries seriesFalse = new XYSeries("False Hits ("+numberFalseMatches+")"); for(Entry<Double,Integer> m:topScoringMatchesFalse.entrySet()){ seriesFalse.add(m.getKey(),new Double(1.0*m.getValue()/numberFalseMatches)); } XYSeries seriesAll= new XYSeries("All Hits ("+(numberTrueMatches+numberFalseMatches)+")"); for(Entry<Double,Integer> m:topScoringMatchesAll.entrySet()){ seriesAll.add(m.getKey(),new Double(1.0*m.getValue()/(numberTrueMatches+numberFalseMatches))); } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(seriesTrue); dataset.addSeries(seriesFalse); dataset.addSeries(seriesAll); final JFreeChart chart =ChartFactory.createXYLineChart("Score Distribution", "score", "percentage", dataset); ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+"\\"+name+"_"+fileName+add+".jpg"), chart, 1000, 400); } } public static void writeRankVSPercentage(File outputFile, String add, List<ResultList>[] resultsOriginal, List<List<ResultList>>[] resultsDecoy, int length) throws Exception{ for(List<ResultList> o:resultsOriginal){ for(List<List<ResultList>> ds:resultsDecoy){ String name="RankVSpercentage"; if(ds.size()>1)name+="Mean"; Map<String,int[]> numbers=new TreeMap<String,int[]>(); for(List<ResultList> d:ds){ List<ResultList> merged=ResultList.mergeResults(new List[]{o,d}); for(int i=0;i<merged.size();i++){ ResultList rl=merged.get(i); for(int j=0;j<Math.min(length,rl.results.size());j++){ String key=rl.query.getDB()+"-"+rl.results.get(j).getDB(); if(!numbers.containsKey(key))numbers.put(key, new int[length]); numbers.get(key)[j]=numbers.get(key)[j]+1; } } } String fileName=""; final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for(Entry<String, int[]> n:numbers.entrySet()){ double all=0; for(int i=0;i<n.getValue().length;i++){ dataset.addValue(n.getValue()[i], n.getKey(), Integer.toString(i)); } fileName+=n.getKey()+"---"; } fileName=fileName.substring(0,fileName.length()-3); final JFreeChart chart = ChartFactory.createBarChart("Boxplot","Ranks","Percentage",dataset); ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+"\\"+name+"_"+fileName+add+".jpg"), chart, Math.min(2000,length*100), 1000); } } } // public static void writeRankVSPercentageFilteredByInchi(File outputFile, String add, List<ResultList>[] resultsOriginal, List<List<ResultList>>[] resultsDecoy, int length) throws Exception{ // // for(List<ResultList> o:resultsOriginal){ // for(List<List<ResultList>> ds:resultsDecoy){ // String name="RankVSpercentageFiltered"; // if(ds.size()>1)name+="Mean"; // Map<String,int[]> numbers=new TreeMap<String,int[]>(); // for(List<ResultList> d:ds){ // List<ResultList> merged=ResultList.mergeResults(new List[]{o,d}); // for(int i=0;i<merged.size();i++){ // ResultList rl=new ResultList(merged.get(i)); // rl.filterResultsByInChi(); // merged.set(i,rl); // for(int j=0;j<Math.min(length,rl.results.size());j++){ // String key=rl.query.getDB()+"-"+rl.results.get(j).getDB(); // if(!numbers.containsKey(key))numbers.put(key, new int[length]); // numbers.get(key)[j]=numbers.get(key)[j]+1; // } // } // } // // String fileName=""; // final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // for(Entry<String, int[]> n:numbers.entrySet()){ // double all=0; // for(int i=0;i<n.getValue().length;i++){ // dataset.addValue(n.getValue()[i], n.getKey(), Integer.toString(i)); // } // fileName+=n.getKey()+"---"; // } // // fileName=fileName.substring(0,fileName.length()-3); // // final JFreeChart chart = ChartFactory.createBarChart("Boxplot","Ranks","Percentage",dataset); // ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+"\\"+name+"_"+fileName+add+".jpg"), chart, Math.min(2000,length*100), 1000); // } // } // } public static void writeEstimatedQValueVSCalculatedQValue(File outputFile, String add, List<ResultList>[] resultsOriginal, List<List<ResultList>>[] resultsDecoy) throws Exception{ for(List<ResultList> o:resultsOriginal){ for(List<List<ResultList>> ds:resultsDecoy){ String name="qValuesComparison"; if(ds.size()>1)name+="Mean"; XYSeries series = null; String fileName=null; for(List<ResultList> d:ds){ List<Result> topScores=new ArrayList<Result>(); String fileNameLeft=""; for(ResultList rl:o){ if(!rl.results.isEmpty()){ topScores.add(rl.results.get(0)); fileNameLeft=rl.query.getDB()+"_"+rl.results.get(0).getDB(); } } String fileNameRight=""; for(ResultList rl:d){ if(!rl.results.isEmpty()){ topScores.add(rl.results.get(0)); fileNameRight=rl.query.getDB()+"_"+rl.results.get(0).getDB(); } } Collections.sort(topScores); if(fileName==null)fileName=fileNameLeft+"---"+fileNameRight; List<Double> FDRByDecoy=new ArrayList<Double>(); List<Double> FDRCalculated=new ArrayList<Double>(); int countTrueMatches=0; int countFalseMatches=0; int countDecoyMatches=0; for(Result r:topScores){ if(r.massbank.isDecoy()){ countDecoyMatches++; }else{ if(r.isTrueMatch){ countTrueMatches++; }else{ countFalseMatches++; } FDRByDecoy.add(2.0*countDecoyMatches/(countDecoyMatches+countTrueMatches+countFalseMatches)); FDRCalculated.add(1.0*countFalseMatches/(countFalseMatches+countTrueMatches)); } } double min=Double.POSITIVE_INFINITY; for(int i=FDRByDecoy.size()-1;i>=0;i--){ min=Math.min(FDRByDecoy.get(i),min); FDRByDecoy.set(i, min); } min=Double.POSITIVE_INFINITY; for(int i=FDRCalculated.size()-1;i>=0;i--){ min=Math.min(FDRCalculated.get(i),min); FDRCalculated.set(i, min); } if(series==null)series=new XYSeries("q-Values " + fileName); for(int i=0;i<FDRByDecoy.size();i++){ series.add(FDRByDecoy.get(i), FDRCalculated.get(i)); } } XYSeriesCollection dataset = new XYSeriesCollection(series); XYSeries seriesWH=new XYSeries("bisecting line"); for(double i=0;i<=1;i+=0.05)seriesWH.add(i,i); dataset.addSeries(seriesWH); final JFreeChart chart = ChartFactory.createScatterPlot("q-Values", "q-values by decoy database", "calculated q-values", dataset); ChartUtilities.saveChartAsJPEG(new File(outputFile.getAbsolutePath()+"\\"+name+"_"+fileName+add+".jpg"), chart, 1000, 1000); } } } }
11,452
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
Utils.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/Utils.java
package de.unijena.bioinf.statistics; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Map; import java.util.TreeMap; import de.unijena.bioinf.decoy.model.MassBank; public class Utils { public static void quicksort(double[] main, int[] index) { quicksort(main, index, 0, index.length - 1); } // quicksort a[left] to a[right] public static void quicksort(double[] a, int[] index, int left, int right) { if (right <= left) return; int i = partition(a, index, left, right); quicksort(a, index, left, i-1); quicksort(a, index, i+1, right); } // partition a[left] to a[right], assumes left < right private static int partition(double[] a, int[] index, int left, int right) { int i = left - 1; int j = right; while (true) { while (less(a[++i], a[right])) // find item on left to swap ; // a[right] acts as sentinel while (less(a[right], a[--j])) // find item on right to swap if (j == left) break; // don't go out-of-bounds if (i >= j) break; // check if pointers cross exch(a, index, i, j); // swap two elements into place } exch(a, index, i, right); // swap with partition element return i; } // is x < y ? private static boolean less(double x, double y) { double first=Double.isNaN(x)?Double.NEGATIVE_INFINITY:x; double second=Double.isNaN(y)?Double.NEGATIVE_INFINITY:y; return (first > second); } // exchange a[i] and a[j] private static void exch(double[] a, int[] index, int i, int j) { double swap = a[i]; a[i] = a[j]; a[j] = swap; int b = index[i]; index[i] = index[j]; index[j] = b; } public static TreeMap<String, MassBank> getAllDBFiles(File[] inputFiles, String ser, boolean forceRecalculation, boolean withPeaks)throws Exception { TreeMap<String, MassBank> dbFiles=null; if(!forceRecalculation){ try{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(ser)); dbFiles = (TreeMap<String, MassBank>) ois.readObject(); ois.close(); }catch(Exception e){ System.err.println(e); } } if(dbFiles==null){ System.out.println("calculating database file..."); dbFiles=new TreeMap<String,MassBank>(); for(File f:inputFiles){ getAllDBFiles(f, dbFiles, withPeaks); } ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(ser)); oos.writeObject(dbFiles); oos.flush(); oos.close(); System.out.println("...finished"); } return dbFiles; } public static void getAllDBFiles(File dbFolder, Map<String, MassBank> results, boolean withPeaks) throws Exception{ if(dbFolder.exists()){ for(File f:dbFolder.listFiles()){ if(f.isFile()&&f.getName().endsWith(".txt")){ results.put(SimilarityMatrix.getIDDatasetChargeOrigin(f.getName().replaceAll(".txt","")), new MassBank(f, withPeaks)); System.out.println(f.getAbsolutePath()); }else if (f.isDirectory()){ getAllDBFiles(f,results, withPeaks); } } } } }
3,326
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
SimilarityMatrix.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/SimilarityMatrix.java
package de.unijena.bioinf.statistics; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.Map.Entry; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.statistics.DefaultBoxAndWhiskerCategoryDataset; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import de.unijena.bioinf.decoy.model.MassBank; public class SimilarityMatrix { public static enum DatabaseType{Decoy, Original}; public static enum MatchType{TruePositiveMatch, FalsePositiveMatch, DecoyMatch}; public List<File> similarityFiles=new ArrayList<File>(); public Map<String,DatabaseType> typesQuery=new TreeMap<String, DatabaseType>(); public Map<String,DatabaseType> typesDB=new TreeMap<String, DatabaseType>(); public List<String> methodsQuery=new ArrayList<String>(); public List<String> methodsDB=new ArrayList<String>(); public List<MassBank> massbankQuery=new ArrayList<MassBank>(); public List<MassBank> massbankDB=new ArrayList<MassBank>(); double[][] similarity; public int[][] commonPeaks; public boolean[][] exclusionListDB; static final String sep=System.getProperty("file.separator"); public SimilarityMatrix(File similarityFile, TreeMap<String,MassBank> massbank) throws Exception{ this.similarityFiles.add(similarityFile); BufferedReader br=new BufferedReader(new FileReader(similarityFile)); String methodsQueryTmp=getMethodFromFilename(br.readLine().replaceAll(";", "").split(" ")[1]); String methodsDBTmp=getMethodFromFilename(br.readLine().replaceAll(";", "").split(" ")[1]); this.typesQuery.put(methodsQueryTmp,methodsQueryTmp.contains("Original")?DatabaseType.Original:DatabaseType.Decoy); this.typesDB.put(methodsDBTmp, methodsDBTmp.contains("Original")?DatabaseType.Original:DatabaseType.Decoy); br.readLine(); if(similarityFile.getName().endsWith(".csv")){ String[] header=br.readLine().substring(1).split(","); for(String s:header){ methodsDB.add(methodsDBTmp); massbankDB.add(massbank.get(getIDDatasetChargeOrigin(s))); } String line; while((line=br.readLine())!=null){ String tmp=line.substring(0,line.indexOf(",")); methodsQuery.add(methodsQueryTmp); massbankQuery.add(massbank.get(getIDDatasetChargeOrigin(tmp))); } br.close(); similarity=new double[massbankQuery.size()][massbankDB.size()]; commonPeaks=new int[massbankQuery.size()][massbankDB.size()]; br=new BufferedReader(new FileReader(similarityFile)); br.readLine();br.readLine();br.readLine();br.readLine(); int r=0; while((line=br.readLine())!=null){ String[] tmp=line.substring(line.indexOf(",")+1).split(","); int c=0; for(String s:tmp){ if(s.contains(" ")){ similarity[r][c]=Double.parseDouble(s.split(" ")[0]); commonPeaks[r][c]=Integer.parseInt(s.split(" ")[1]); }else{ similarity[r][c]=Double.parseDouble(s); commonPeaks[r][c]=0; } c++; } r++; } }else{ String line; while((line=br.readLine())!=null){ if(line.startsWith("query")){ MassBank mb=massbank.get(getIDDatasetChargeOrigin(line.split("\\t")[1])); if(!massbankQuery.contains(mb)){ massbankQuery.add(mb); methodsQuery.add(methodsQueryTmp); } } if(line.startsWith("result")){ MassBank mb=massbank.get(getIDDatasetChargeOrigin(line.split("\\t")[1])); if(!massbankDB.contains(mb)){ massbankDB.add(mb); methodsDB.add(methodsDBTmp); } } } String querySub=""; if(massbankQuery.size()==0){ querySub=methodsQueryTmp.startsWith("MetlinPositive")?methodsQueryTmp.replaceAll("MetlinPositiv", "MP"):methodsQueryTmp.replaceAll("AgilentPositiv", "AP"); }else{ querySub=massbankQuery.get(0).massbankID.replaceAll("\\d", ""); } querySub=getIDDatasetChargeOrigin(querySub); for(MassBank mb:massbank.values()) if(mb.massbankID.startsWith(querySub)&&!massbankQuery.contains(mb)){ massbankQuery.add(mb); methodsQuery.add(methodsQueryTmp); } String dbSub=""; if(massbankDB.size()==0){ dbSub=methodsDBTmp.startsWith("MetlinPositive")?methodsDBTmp.replaceAll("MetlinPositive", "MP"):methodsDBTmp.replaceAll("AgilentPositive", "AP"); }else{ dbSub=massbankDB.get(0).massbankID.replaceAll("\\d", ""); } dbSub=getIDDatasetChargeOrigin(dbSub); for(MassBank mb:massbank.values()) if(mb.massbankID.startsWith(dbSub)&&!massbankDB.contains(mb)){ massbankDB.add(mb); methodsDB.add(methodsDBTmp); } br.close(); similarity=new double[massbankQuery.size()][massbankDB.size()]; commonPeaks=new int[massbankQuery.size()][massbankDB.size()]; br=new BufferedReader(new FileReader(similarityFile)); int indexQuery=Integer.MAX_VALUE; while((line=br.readLine())!=null){ if(line.startsWith("query")){ MassBank mb=massbank.get(getIDDatasetChargeOrigin(line.split("\\t")[1])); indexQuery=massbankQuery.indexOf(mb); } if(line.startsWith("result")){ String l[]=line.split("\\t"); MassBank mb=massbank.get(getIDDatasetChargeOrigin(l[1])); int indexDB=massbankDB.indexOf(mb); similarity[indexQuery][indexDB]=Double.parseDouble(l[4]); commonPeaks[indexQuery][indexDB]=Integer.parseInt(l[3]); } } } br.close(); clearExclusionList(); } public SimilarityMatrix(){} public SimilarityMatrix(List<SimilarityMatrix> matrices) throws Exception{ for(SimilarityMatrix m:matrices){ similarityFiles.addAll(m.similarityFiles); typesQuery.putAll(m.typesQuery); typesDB.putAll(m.typesDB); massbankDB.addAll(m.massbankDB); methodsDB.addAll(m.methodsDB); if(massbankQuery.isEmpty()){ massbankQuery.addAll(m.massbankQuery); methodsQuery.addAll(m.methodsQuery); }else{ if(!massbankQuery.containsAll(m.massbankQuery)|| !m.massbankQuery.containsAll(massbankQuery)|| !methodsQuery.containsAll(m.methodsQuery)|| !m.methodsQuery.containsAll(methodsQuery)){ throw new Exception("No merge possible as the query was not the same!"); } } } similarity=new double[massbankQuery.size()][massbankDB.size()]; commonPeaks=new int[massbankQuery.size()][massbankDB.size()]; clearExclusionList(); for(MassBank mb:massbankQuery){ int c=0; for(SimilarityMatrix m:matrices){ int r=m.massbankQuery.indexOf(mb); for(int i=0;i<m.similarity[r].length;i++){ similarity[r][c]=m.similarity[r][i]; commonPeaks[r][c]=m.commonPeaks[r][i]; exclusionListDB[r][c]=m.exclusionListDB[r][i]; c++; } } } } public void clearExclusionList(){ exclusionListDB=new boolean[similarity.length][similarity[0].length]; for(int i=0;i<exclusionListDB.length;i++){ for(int j=0;j<exclusionListDB[i].length;j++){ exclusionListDB[i][j]=Boolean.FALSE; } } } public static void clearExclusionLists(List<SimilarityMatrix> matrices){ for(SimilarityMatrix m:matrices){ m.clearExclusionList(); } } public void excludeSameInChi(){ for(int i=0;i<massbankQuery.size();i++){ for(int j=0;j<massbankDB.size();j++){ if(massbankQuery.get(i).hasEqualInChiKey(massbankDB.get(j))){ exclusionListDB[i][j]=Boolean.TRUE; } } } } public static void excludeSameInChi(List<SimilarityMatrix> matrices){ for(SimilarityMatrix m:matrices){ m.excludeSameInChi(); } } public void excludeZeroEntries(){ for(int i=0;i<massbankQuery.size();i++){ for(int j=0;j<massbankDB.size();j++){ if(similarity[i][j]==0){ exclusionListDB[i][j]=Boolean.TRUE; } } } } public void excludeDifferentMass(double ppm, double ae){ for(int i=0;i<massbankQuery.size();i++){ for(int j=0;j<massbankDB.size();j++){ if(!massbankQuery.get(i).hasEqualMass(massbankDB.get(j), ppm, ae)){ exclusionListDB[i][j]=Boolean.TRUE; } } } } public void excludeMassBanksFromDB(Map<MassBank, List<MassBank>> mb){ for(int i=0;i<massbankQuery.size();i++){ List<MassBank> currMB=mb.get(massbankQuery.get(i)); if(currMB==null)continue; for(int j=0;j<massbankDB.size();j++){ if(currMB.contains(massbankDB.get(j))){ exclusionListDB[i][j]=Boolean.TRUE; } } } } public void excludeDifferentFormulas(){ for(int i=0;i<massbankQuery.size();i++){ for(int j=0;j<massbankDB.size();j++){ if(!massbankQuery.get(i).mf.equals(massbankDB.get(j).mf)){ exclusionListDB[i][j]=Boolean.TRUE; } } } } public static void excludeDifferentMasses(List<SimilarityMatrix> matrices, double ppm, double ae){ for(SimilarityMatrix m:matrices){ m.excludeDifferentMass(ppm, ae); } } public static double getAbsoluteErrorForMass(double precursor, double ppm, double ae) { return Math.max(ppm*1e-6*precursor, ae*1e-3); } public static void excludeZeroEntries(List<SimilarityMatrix> matrices){ for(SimilarityMatrix m:matrices){ m.excludeZeroEntries(); } } public boolean isExcluded(MassBank query, MassBank db){ return exclusionListDB[massbankQuery.indexOf(query)][massbankDB.indexOf(db)]; } public double getSimilarityValue(int i,int j){ if(exclusionListDB[i][j])return Double.NaN; return similarity[i][j]; } static public String getIDDatasetChargeOrigin(String methodID){ return methodID.substring(0,7)+methodID.replaceAll("\\D", ""); } static public String getIDDatasetCharge(String methodID){ return methodID.substring(0,2)+methodID.replaceAll("\\D", ""); } public int[][] getIndizesOfSortedScores(){ int[][] result=new int[methodsQuery.size()][methodsDB.size()]; for(int i=0;i<result.length;i++){ for(int k=0;k<result[i].length;k++){ result[i][k]=k; } } for(int i=0;i<result.length;i++){ double[] similarityTmp=new double[methodsDB.size()]; for(int k=0;k<similarityTmp.length;k++){ similarityTmp[k]=getSimilarityValue(i,k); } Utils.quicksort(similarityTmp,result[i]); } return result; } public XYSeries getEstimatedQValueVSCalculatedQValue(boolean FDR, List<MassBank> compoundsOfInterest, String number, double minCalcValue, double maxCalcValue) throws IOException{ int[][] sortedIndizes=getIndizesOfSortedScores(); List<Double> bestScores=new ArrayList<Double>(); List<MatchType> matches=new ArrayList<MatchType>(); for(int i=0;i<sortedIndizes.length;i++){ if(!compoundsOfInterest.contains(massbankQuery.get(i)))continue; boolean foundOriginal=false; boolean foundDecoy=false; for(int j=0;j<sortedIndizes[i].length;j++){ int currCol=sortedIndizes[i][j]; if(Double.isNaN(getSimilarityValue(i,currCol)))continue; String method=methodsDB.get(currCol); if(!foundOriginal&&typesDB.get(method)==DatabaseType.Original){ bestScores.add(getSimilarityValue(i,currCol)); if(massbankQuery.get(i).hasEqualInChiKey(massbankDB.get(currCol))){ matches.add(MatchType.TruePositiveMatch); }else{ matches.add(MatchType.FalsePositiveMatch); } foundOriginal=true; } if(!foundDecoy&&typesDB.get(method)==DatabaseType.Decoy){ bestScores.add(getSimilarityValue(i,currCol)); matches.add(MatchType.DecoyMatch); foundDecoy=true; } if(foundOriginal&&foundDecoy)break; } } int[] indizes=new int[bestScores.size()]; double[] scores=new double[bestScores.size()]; for(int i=0;i<indizes.length;i++)indizes[i]=i; for(int i=0;i<scores.length;i++)scores[i]=bestScores.get(i); Utils.quicksort(scores,indizes); List<Double> FDRByDecoy=new ArrayList<Double>(); List<Double> FDRCalculated=new ArrayList<Double>(); int countTrueMatches=0; int countFalseMatches=0; int countDecoyMatches=0; for(int i:indizes){ if(matches.get(i)==MatchType.DecoyMatch){ countDecoyMatches++; }else{ if(matches.get(i)==MatchType.TruePositiveMatch){ countTrueMatches++; }else{ countFalseMatches++; } // FDRByDecoy.add(2.0*countDecoyMatches/(countDecoyMatches+countTrueMatches+countFalseMatches)); FDRByDecoy.add(1.0*countDecoyMatches/(countTrueMatches+countFalseMatches)); FDRCalculated.add(1.0*countFalseMatches/(countFalseMatches+countTrueMatches)); } } FDRByDecoy.add(2.0*countDecoyMatches/(countDecoyMatches+countTrueMatches+countFalseMatches)); FDRCalculated.add(1.0*countFalseMatches/(countFalseMatches+countTrueMatches)); if(!FDR){ double min=Double.POSITIVE_INFINITY; for(int i=FDRByDecoy.size()-1;i>=0;i--){ min=Math.min(FDRByDecoy.get(i),min); FDRByDecoy.set(i, min); } min=Double.POSITIVE_INFINITY; for(int i=FDRCalculated.size()-1;i>=0;i--){ min=Math.min(FDRCalculated.get(i),min); FDRCalculated.set(i, min); } } for(int i=FDRCalculated.size()-1;i>=0;i--){ if(FDRCalculated.get(i)<minCalcValue||FDRCalculated.get(i)>maxCalcValue){ FDRCalculated.remove(i); FDRByDecoy.remove(i); } } XYSeries series=new XYSeries((FDR?"FDR":"q-Values")+" " +number+" "+ getMethodsQueryAndDBString()); for(int i=0;i<FDRByDecoy.size();i++){ series.add(FDRCalculated.get(i),FDRByDecoy.get(i)); } return series; } public static XYSeries getBisectingLine(double min, double max){ XYSeries seriesWH=new XYSeries("bisecting line"); for(double i=min;i<=max;i+=(max-min)/10)seriesWH.add(i,i); return seriesWH; } public static void writeEstimatedQValueVSCalculatedQValue(File outputFile, List<SimilarityMatrix> matrices, String add, double percentage, int repeat, double minCalcValue, double maxCalcValue) throws IOException{ writeEstimatedQValueVSCalculatedQValue(outputFile, matrices, add, false, percentage, repeat, minCalcValue, maxCalcValue); } public static void writeEstimatedFDRVSCalculatedFDR(File outputFile, List<SimilarityMatrix> matrices, String add, double percentage, int repeat, double minCalcValue, double maxCalcValue) throws IOException{ writeEstimatedQValueVSCalculatedQValue(outputFile, matrices, add, true, percentage, repeat, minCalcValue, maxCalcValue); } public static void writeEstimatedQValueVSCalculatedQValue(File outputFile, List<SimilarityMatrix> matrices, String add, boolean FDR, double percentage, int repeat, double minCalcValue, double maxCalcValue) throws IOException{ Random r=new Random(); List<List<MassBank>> compoundsOfInterest=new ArrayList<List<MassBank>>(); for(int i=0;i<repeat;i++){ List<MassBank> allMassBanks=new ArrayList<MassBank>(matrices.get(0).massbankQuery); int size=allMassBanks.size(); List<MassBank> finalMassBanks=new ArrayList<MassBank>(); while(finalMassBanks.size()<percentage*size){ int n=r.nextInt(allMassBanks.size()); finalMassBanks.add(allMassBanks.get(n)); allMassBanks.remove(n); } compoundsOfInterest.add(allMassBanks); } for(SimilarityMatrix m:matrices){ m.writeEstimatedQValueVSCalculatedQValue(outputFile, add, FDR, compoundsOfInterest, minCalcValue, maxCalcValue); } } public void writeEstimatedQValueVSCalculatedQValue(File outputFile, String add, boolean FDR, List<List<MassBank>> compoundsOfInterest, double minCalcValue, double maxCalcValue) throws IOException{ XYSeriesCollection dataset = new XYSeriesCollection(); List<XYSeries> series=new ArrayList<XYSeries>(); for(int i=0;i<compoundsOfInterest.size();i++){ // System.out.println(i); List<MassBank> finalMassBanks=compoundsOfInterest.get(i); // series.add(this.getEstimatedQValueVSCalculatedQValue(FDR, finalMassBanks, Integer.toString(i), minCalcValue, maxCalcValue)); series.add(this.getEstimatedQValueVSCalculatedQValue(FDR, finalMassBanks, "", minCalcValue ,maxCalcValue)); } String desc=FDR?"FDRsComparisonMultiple_":"qValuesComparisonMultiple_"; String desc2=FDR?"FDRs":"qValues"; BufferedWriter bw=new BufferedWriter(new FileWriter(new File(outputFile.getAbsolutePath()+sep+add+desc+getMethodsQueryAndDBString()+".txt"))); XYSeries xyseries=new XYSeries(series.get(0).getKey()); double sum=0; int count=0; for(XYSeries s:series){ double sum2=0; int count2=0; for(Object iTmp:s.getItems()){ XYDataItem i=(XYDataItem) iTmp; xyseries.add(i.getXValue(), i.getYValue()); double curr=Math.pow(i.getXValue()-i.getYValue(),2); sum2+=curr; count2++; } bw.write(s.getKey()+"\t"+count2+"\t"+sum2+"\t"+1.0*sum2/count2);bw.newLine(); if(count2!=0){ sum+=1.0*sum2/count2; count++; } } bw.write("average sum\t"+count+"\t"+sum+"\t"+1.0*sum/count);bw.newLine(); bw.close(); dataset.addSeries(xyseries); XYSeries seriesWH=getBisectingLine(minCalcValue, maxCalcValue); dataset.addSeries(seriesWH); final JFreeChart chart = ChartFactory.createScatterPlot(desc2, desc2 +" calculated", desc2+" by decoy database", dataset); ChartUtilities.saveChartAsJPEG(new File(outputFile.getAbsolutePath()+sep+add+desc+getMethodsQueryAndDBString()+".jpg"), chart, 1000, 1000); } public static void writeEstimatedQValueVSCalculatedQValue(File outputFile, List<SimilarityMatrix> matrices, String add, boolean FDR) throws IOException{ XYSeriesCollection dataset = new XYSeriesCollection(); for(SimilarityMatrix m:matrices){ dataset.addSeries(m.getEstimatedQValueVSCalculatedQValue(FDR, m.massbankQuery,"",Double.NEGATIVE_INFINITY,Double.POSITIVE_INFINITY)); } XYSeries seriesWH=getBisectingLine(0, 1); dataset.addSeries(seriesWH); String desc=FDR?"FDRsComparison_":"qValuesComparison_"; String desc2=FDR?"FDRs":"qValues"; final JFreeChart chart = ChartFactory.createScatterPlot(desc2, desc2+" calculated", desc2+" by decoy database", dataset); ChartUtilities.saveChartAsJPEG(new File(outputFile.getAbsolutePath()+sep+add+desc+getMethodsQueryStringFromList(matrices)+".jpg"), chart, 1000, 1000); } public void writeEstimatedQValueVSCalculatedQValue(File outputFile, String add) throws IOException{ SimilarityMatrix.writeEstimatedQValueVSCalculatedQValue(outputFile, Arrays.asList(new SimilarityMatrix[]{this}), add, false); } public void writeEstimatedFDRVSCalculatedFDR(File outputFile, String add) throws IOException{ SimilarityMatrix.writeEstimatedQValueVSCalculatedQValue(outputFile, Arrays.asList(new SimilarityMatrix[]{this}), add, true); } public static void writeEstimatedQValueVSCalculatedQValue(File outputFile, List<SimilarityMatrix> matrices, String add) throws IOException{ SimilarityMatrix.writeEstimatedQValueVSCalculatedQValue(outputFile, matrices, add, false); } public static void writeEstimatedFDRVSCalculatedFDR(File outputFile, List<SimilarityMatrix> matrices, String add) throws IOException{ SimilarityMatrix.writeEstimatedQValueVSCalculatedQValue(outputFile, matrices, add, true); } public String getMethodsQueryAndDBString(){ return getMethodsQueryString()+"---"+getMethodsDBString(); } public String getMethodsQueryString(){ String result=""; for(String s:typesQuery.keySet())result+="_"+s; return result.substring(1).replaceAll("[a-z]",""); } public String getMethodsDBString(){ String result=""; for(String s:typesDB.keySet())result+="_"+s; return result.substring(1).replaceAll("[a-z]",""); } private String getMethodFromFilename(String s){ String[] tmp=s.split(s.contains("/")?"/":"\\\\"); return tmp[tmp.length-2]; } // public void writeScoresOfSameCompounds(File outputFile, String add) throws Exception{ // HashMap<String, Map<MassBank,Integer>> massbank2indexDB=new HashMap<String, Map<MassBank,Integer>>(); // List<String> massbankMethods=new ArrayList<String>(); // List<MassBank> massbankEntries=new ArrayList<MassBank>(); // for(String t:methodsDB)if(!massbank2indexDB.containsKey(t))massbank2indexDB.put(t, new HashMap<MassBank,Integer>()); // for(int i=0;i<massbankDB.size();i++){ // MassBank mb=massbankDB.get(i); // String method=methodsDB.get(i); // massbank2indexDB.get(method).put(mb,i); // if(!massbankMethods.contains(method))massbankMethods.add(method); // if(!massbankEntries.contains(mb))massbankEntries.add(mb); // } // // XYSeriesCollection dataset = new XYSeriesCollection(); // Map<String, XYSeries> seriesMap=new HashMap<String, XYSeries>(); // int[][] sortedIndizes=getIndizesOfSortedScores(); // for(int i=0;i<sortedIndizes.length;i++){ // for(int m=0;m<1;m++){ // int ind=sortedIndizes[i][m]; // MassBank mb=massbankDB.get(ind); // double valueOrig=getSimilarityValue(i,ind); // if(Double.isNaN(valueOrig))continue; // for(int j=0;j<massbankMethods.size()-1;j++){ // for(int k=j+1;k<massbankMethods.size();k++){ // String methodsA=(methodsDB.get(j).compareTo(massbankMethods.get(k))<0)?massbankMethods.get(j):massbankMethods.get(k); // String methodsB=(methodsDB.get(j).compareTo(massbankMethods.get(k))<0)?massbankMethods.get(k):massbankMethods.get(j); // String key=methodsQuery.get(i)+" "+methodsA+" "+methodsB; // int indexA=massbank2indexDB.get(methodsA).get(mb); // int indexB=massbank2indexDB.get(methodsB).get(mb); // if(!seriesMap.containsKey(key)){ // String description="DB: "+methodsQuery.get(i)+", "+methodsA+" vs. "+methodsB; // XYSeries series=new XYSeries(description); // seriesMap.put(key, series); // dataset.addSeries(series); // } // seriesMap.get(key).add(getSimilarityValue(i,indexA),getSimilarityValue(i,indexB)); // } // } // } // } // XYSeries seriesWH=getBisectingLine(0,1); // dataset.addSeries(seriesWH); // // final JFreeChart chart = ChartFactory.createScatterPlot("Score 1 vs. Score 2", "Score 1", "Score2", dataset); // ChartUtilities.saveChartAsJPEG(new File(outputFile.getAbsolutePath()+sep+add+"ScoresOfSameCompounds_"+getMethodsQueryAndDBString()+".jpg"), chart, 1000, 1000); // } // public void writeScoreDistributionOfTopRank(File outputFile, double step, String add) throws Exception{ // Map<Double, Integer> topScoringMatchesAll=new TreeMap<Double,Integer>(); // Map<Double, Integer> topScoringMatchesTrue=new TreeMap<Double,Integer>(); // Map<Double, Integer> topScoringMatchesFalse=new TreeMap<Double,Integer>(); // int numberTrueMatches=0; // int numberFalseMatches=0; // // int[][] sortedIndizes=getIndizesOfSortedScores(); // // for(int i=0;i<sortedIndizes.length;i++){ // int ind=sortedIndizes[i][0]; // double valueOrig=getSimilarityValue(i,ind); // if(Double.isNaN(valueOrig))continue; // double value=Math.round(valueOrig/step)*step; // if(!topScoringMatchesAll.containsKey(value))topScoringMatchesAll.put(value, 0); // topScoringMatchesAll.put(value,topScoringMatchesAll.get(value)+1); // if(massbankQuery.get(i).hasEqualInChiKey(massbankDB.get(ind))){ // if(!topScoringMatchesTrue.containsKey(value))topScoringMatchesTrue.put(value, 0); // topScoringMatchesTrue.put(value,topScoringMatchesTrue.get(value)+1); // numberTrueMatches++; // }else{ // if(!topScoringMatchesFalse.containsKey(value))topScoringMatchesFalse.put(value, 0); // topScoringMatchesFalse.put(value,topScoringMatchesFalse.get(value)+1); // numberFalseMatches++; // } // } // // XYSeries seriesTrue = new XYSeries("True Hits ("+numberTrueMatches+")"); // for(Entry<Double,Integer> m:topScoringMatchesTrue.entrySet()){ // seriesTrue.add(m.getKey(),new Double(1.0*m.getValue()/numberTrueMatches)); // } // XYSeries seriesFalse = new XYSeries("False Hits ("+numberFalseMatches+")"); // for(Entry<Double,Integer> m:topScoringMatchesFalse.entrySet()){ // seriesFalse.add(m.getKey(),new Double(1.0*m.getValue()/numberFalseMatches)); // } // XYSeries seriesAll= new XYSeries("All Hits ("+(numberTrueMatches+numberFalseMatches)+")"); // for(Entry<Double,Integer> m:topScoringMatchesAll.entrySet()){ // seriesAll.add(m.getKey(),new Double(1.0*m.getValue()/(numberTrueMatches+numberFalseMatches))); // } // // XYSeriesCollection dataset = new XYSeriesCollection(); // dataset.addSeries(seriesTrue); // dataset.addSeries(seriesFalse); // dataset.addSeries(seriesAll); // // final JFreeChart chart =ChartFactory.createXYLineChart("Score Distribution", "score", "percentage", dataset); // ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+sep+add+"ScoreDistributionTopRank"+"_"+getMethodsQueryAndDBString()+".jpg"), chart, 1000, 400); // } public double[] writeROCCurveOfTopRank(File outputFile, double step, String add) throws Exception{ double AUC=0; double F=0; int countF=0; TreeMap<Double, List<MatchType>> topScoringMatches=new TreeMap<Double,List<MatchType>>(Collections.reverseOrder()); int[][] sortedIndizes=getIndizesOfSortedScores(); int allPositives=0; int allNegatives=0; for(int i=0;i<sortedIndizes.length;i++){ int ind=sortedIndizes[i][0]; double value=getSimilarityValue(i,ind); if(Double.isNaN(value))continue; if(!topScoringMatches.containsKey(value))topScoringMatches.put(value, new ArrayList<MatchType>()); if(massbankQuery.get(i).hasEqualInChiKey(massbankDB.get(ind))){ topScoringMatches.get(value).add(MatchType.TruePositiveMatch); allPositives++; }else{ topScoringMatches.get(value).add(MatchType.FalsePositiveMatch); allNegatives++; } } List<double[]> values=new ArrayList<double[]>(); XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries series=new XYSeries("ROCCurve " + getMethodsQueryAndDBString()); double currentNumberTruePositives=0; double currentNumberFalsePositives=0; for(Entry<Double, List<MatchType>> matches:topScoringMatches.entrySet()){ for(MatchType m:matches.getValue()){ if(m.equals(MatchType.TruePositiveMatch))currentNumberTruePositives++; if(m.equals(MatchType.FalsePositiveMatch))currentNumberFalsePositives++; } double sensitivity=1.0*currentNumberTruePositives/allPositives; double EinsMinusSpecificity=1.0*currentNumberFalsePositives/allNegatives; values.add(new double[]{EinsMinusSpecificity,sensitivity}); series.add(EinsMinusSpecificity,sensitivity); double precision=1.0*currentNumberTruePositives/(currentNumberTruePositives+currentNumberFalsePositives); F+=matches.getValue().size()*2*precision*sensitivity/(precision+sensitivity); countF+=matches.getValue().size(); } dataset.addSeries(series); F/=countF; double lastX=0; for(int i=1;i<values.size();i++){ if(values.get(i-1)[0]!=values.get(i)[0]){ AUC+=values.get(i-1)[1]*(values.get(i)[0]-lastX); lastX=values.get(i)[0]; } } final JFreeChart chart = ChartFactory.createScatterPlot("ROCCurve","False Positive Rate", "True Positive Rate", dataset); ChartUtilities.saveChartAsJPEG(new File(outputFile.getAbsolutePath()+sep+add+"ROCCurveOfTopRank_"+getMethodsQueryAndDBString()+".jpg"), chart, 1000, 1000); return new double[]{AUC,F}; } public void writeRankVSPercentage(File outputFile, int length, String add) throws Exception{ int[][] sortedIndizes=getIndizesOfSortedScores(); Map<String,int[]> numbers=new TreeMap<String,int[]>(); numbers.put("Decoy", new int[Math.min(length,sortedIndizes[0].length)]); numbers.put("Original", new int[Math.min(length,sortedIndizes[0].length)]); for(int i=0;i<sortedIndizes.length;i++){ int l=0; for(int j=0;j<sortedIndizes[i].length;j++){ int currCol=sortedIndizes[i][j]; if(Double.isNaN(getSimilarityValue(i,currCol)))continue; String method=methodsDB.get(currCol); if(typesDB.get(method)==DatabaseType.Original){ numbers.get("Original")[l]=numbers.get("Original")[l]+1; }else if(typesDB.get(method)==DatabaseType.Decoy){ numbers.get("Decoy")[l]=numbers.get("Decoy")[l]+1; } l++; if(l>=numbers.get("Original").length)break; } } final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for(Entry<String, int[]> n:numbers.entrySet()){ for(int i=0;i<n.getValue().length;i++){ dataset.addValue(n.getValue()[i], n.getKey(), Integer.toString(i)); } } final JFreeChart chart = ChartFactory.createBarChart("BarChart","Ranks","Percentage",dataset); ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+sep+add+"RankVSpercentage_"+getMethodsQueryAndDBString()+".jpg"), chart, Math.min(2000,length*100), 1000); } // public void writeNumberHitsVSPercentage(File outputFile, String add) throws Exception{ // // TreeMap<Integer,Integer> numbers=new TreeMap<Integer,Integer>(); // // for(int i=0;i<massbankQuery.size();i++){ // int countHits=0; // for(int j=0;j<massbankDB.size();j++){ // if(Double.isNaN(getSimilarityValue(i,j)))continue; // countHits++; // } // if(!numbers.containsKey(countHits))numbers.put(countHits, 0); // numbers.put(countHits, numbers.get(countHits)+1); // } // // final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // for(Entry<Integer, Integer> n:numbers.entrySet()){ // dataset.addValue(n.getValue(), "numbers", Integer.toString(n.getKey())); // } // // final JFreeChart chart = ChartFactory.createBarChart("BarChart","Number of Hits","Percentage",dataset); // ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+sep+add+"NumberHitsVSPercentage_"+getMethodsQueryAndDBString()+".jpg"), chart, 2000, 1000); // } public static void writeRankVSScore(File outputFile, List<SimilarityMatrix> matrices, int length, String add) throws Exception{ final DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset(); for(SimilarityMatrix m:matrices){ int[][] sortedIndizes=m.getIndizesOfSortedScores(); List<Double>[] scoreList=new List[Math.min(length,sortedIndizes[0].length)]; for(int i=0;i<scoreList.length;i++)scoreList[i]=new ArrayList<Double>(); for(int i=0;i<sortedIndizes.length;i++){ int l=0; for(int j=0;j<sortedIndizes[i].length;j++){ double v=m.getSimilarityValue(i,sortedIndizes[i][j]); if(!Double.isNaN(v)){ scoreList[l].add(v); l++; } if(l>=scoreList.length)break; } } for(int i=0;i<scoreList.length;i++) dataset.add(scoreList[i], m.getMethodsQueryAndDBString(), i); } JFreeChart chart=ChartFactory.createBoxAndWhiskerChart("Whiskerplot", "Ranks", "Scores", dataset, true); ChartUtilities.saveChartAsJPEG(new File(outputFile.getPath()+sep+add+"RankVSScore_"+getMethodsQueryStringFromList(matrices)+".jpg"), chart, Math.min(2000,length*100), 1000); } public static String getMethodsQueryAndDBStringFromList(List<SimilarityMatrix> matrices){ String name=""; for(SimilarityMatrix m:matrices){ name+="___"+m.getMethodsQueryAndDBString(); } return name.substring(3); } public static String getMethodsDBStringFromList(List<SimilarityMatrix> matrices){ String name=""; for(SimilarityMatrix m:matrices){ name+="___"+m.getMethodsDBString(); } return name.substring(3); } public static String getMethodsQueryStringFromList(List<SimilarityMatrix> matrices){ String name=""; List<String> methods=new ArrayList<String>(); for(SimilarityMatrix m:matrices){ String me = m.getMethodsQueryString(); if(!methods.contains(me)){ methods.add(me); name+="___"+me; } } return name.substring(3); } public int getNumberOfPossibleHits(){ int number=0; for(int i=0;i<similarity.length;i++){ boolean found=false; for(int j=0;j<similarity[i].length;j++){ double currValue=getSimilarityValue(i,j); if(Double.isNaN(currValue))continue; if(massbankQuery.get(i).hasEqualInChiKey(massbankDB.get(j))){ found=true; break; } } if(found)number++; } return number; } public int getNumberOfNonemptySearchLists(){ int number=0; for(int i=0;i<similarity.length;i++){ boolean found=false; for(int j=0;j<similarity[i].length;j++){ double currValue=getSimilarityValue(i,j); if(Double.isNaN(currValue))continue; found=true; break; } if(found)number++; } return number; } public int getNumberOfTrueHits(){ int number=0; int[][] sortedIndizes=getIndizesOfSortedScores(); for(int i=0;i<sortedIndizes.length;i++){ for(int j=0;j<sortedIndizes[i].length;j++){ int currCol=sortedIndizes[i][j]; double currValue=getSimilarityValue(i,currCol); if(Double.isNaN(currValue))continue; if(massbankQuery.get(i).hasEqualInChiKey(massbankDB.get(currCol))){ number++; } break; } } return number; } public List<MassBank> getFirstSortedMassbankEntries(int i, int[] sortedIndizes){ List<MassBank> result=new ArrayList<MassBank>(); double maxValue=Double.NaN; for(int j=0;j<sortedIndizes.length;j++){ int currCol=sortedIndizes[j]; double currValue=getSimilarityValue(i,currCol); if(Double.isNaN(currValue))continue; if(Double.isNaN(maxValue)||maxValue==currValue){ result.add(massbankDB.get(currCol)); maxValue=currValue; }else{ break; } } return result; } public List<List<MassBank>> getSortedMassbankEntries(int i, int[] sortedIndizes){ List<List<MassBank>> result=new ArrayList<List<MassBank>>(); List<MassBank> currResult=new ArrayList<MassBank>(); double currMaxValue=Double.NaN; for(int j=0;j<sortedIndizes.length;j++){ int currCol=sortedIndizes[j]; double currValue=getSimilarityValue(i,currCol); if(Double.isNaN(currValue))continue; if(Double.isNaN(currMaxValue)||Double.compare(currMaxValue,currValue)!=0){ currResult=new ArrayList<MassBank>(); result.add(currResult); } currResult.add(massbankDB.get(currCol)); currMaxValue=currValue; } return result; } public List<List<DatabaseType>> getSortedDatabaseTypes(int i, int[] sortedIndizes){ List<List<DatabaseType>> result=new ArrayList<List<DatabaseType>>(); List<DatabaseType> currResult=new ArrayList<DatabaseType>(); double currMaxValue=Double.NaN; for(int j=0;j<sortedIndizes.length;j++){ int currCol=sortedIndizes[j]; double currValue=getSimilarityValue(i,currCol); if(Double.isNaN(currValue))continue; if(Double.isNaN(currMaxValue)||Double.compare(currMaxValue,currValue)!=0){ currResult=new ArrayList<DatabaseType>(); result.add(currResult); } currResult.add(typesDB.get(methodsDB.get(currCol))); currMaxValue=currValue; } return result; } public List<MassBank> getHitsInDB(MassBank mbQuery){ List<MassBank> result=new ArrayList<MassBank>(); for(MassBank mbDB:massbankDB){ if(mbQuery.hasEqualInChiKey(mbDB)&&!isExcluded(mbQuery, mbDB)) result.add(mbDB); } return result; } public static Map<DatabaseType, Double>[] getRankDistribution(File outputFile, SimilarityMatrix mOriginal, List<SimilarityMatrix> mDecoys, int length) throws Exception{ Map<DatabaseType, Double>[] result=new TreeMap[length]; for(int i=0;i<result.length;i++)result[i]=new TreeMap<DatabaseType, Double>(); for(SimilarityMatrix matrix:mDecoys){ SimilarityMatrix merged=new SimilarityMatrix(Arrays.asList(new SimilarityMatrix[]{mOriginal, matrix})); int[][] sortedIndizes=merged.getIndizesOfSortedScores(); for(int i=0;i<merged.massbankQuery.size();i++){ List<List<DatabaseType>> sortedDatabaseType = merged.getSortedDatabaseTypes(i, sortedIndizes[i]); int j=0; int index=0; while(j<length&&index<sortedDatabaseType.size()){ Map<DatabaseType, Integer> count=new HashMap<DatabaseType,Integer>(); List<DatabaseType> currentTypes=sortedDatabaseType.get(index); for(int k=0;k<currentTypes.size();k++){ if(!count.containsKey(currentTypes.get(k)))count.put(currentTypes.get(k),0); count.put(currentTypes.get(k),count.get(currentTypes.get(k))+1); } for(int k=0;k<currentTypes.size();k++){ if(j<result.length){ for(Entry<DatabaseType,Integer> c:count.entrySet()){ if(!result[j].containsKey(c.getKey()))result[j].put(c.getKey(),0.0); result[j].put(c.getKey(),result[j].get(c.getKey())+1.0*c.getValue()/currentTypes.size()); } j++; } } index++; } } } final DefaultCategoryDataset dataset = new DefaultCategoryDataset(); File txtFile=new File(outputFile.getAbsolutePath().replaceAll(".jpg", ".txt")); BufferedWriter bw=new BufferedWriter(new FileWriter(txtFile)); List<DatabaseType> header=new ArrayList<DatabaseType>(); for(DatabaseType db:DatabaseType.values()){ bw.write("\t"+db.toString()); header.add(db); } bw.newLine(); for(int i=0;i<result.length;i++){ bw.write(Integer.toString(i)); int sum=0; for(Entry<DatabaseType, Double> e:result[i].entrySet()){ sum+=e.getValue(); } double[] values=new double[header.size()]; for(Entry<DatabaseType, Double> e:result[i].entrySet()){ dataset.addValue(e.getValue(), e.getKey(), Integer.toString(i)); values[header.indexOf(e.getKey())]=e.getValue()/sum; } for(double d:values)bw.write("\t"+d); bw.newLine(); } final JFreeChart chart = ChartFactory.createBarChart("Boxplot","Ranks","Percentage",dataset); ChartUtilities.saveChartAsJPEG(outputFile, chart, Math.min(2000,length*100), 1000); bw.close(); return result; } public HitStatistic getHitStatistic(){ HitStatistic hs=new HitStatistic(); hs.m=this; int[][] sortedIndizes=getIndizesOfSortedScores(); for(int i=0;i<sortedIndizes.length;i++){ Hit h=new Hit(); h.massbankQuery=massbankQuery.get(i); h.hitsInDB=getHitsInDB(massbankQuery.get(i)); if(!h.hitsInDB.isEmpty()){ h.minRankBestHit=Integer.MAX_VALUE; h.maxRankBestHit=Integer.MAX_VALUE; h.scoreBestHit=Double.NEGATIVE_INFINITY; } int currentNumberHits=0; List<List<MassBank>> sortedEntries=getSortedMassbankEntries(i, sortedIndizes[i]); if(sortedEntries.size()>0){ for(int j=0;j<sortedEntries.size();j++){ List<MassBank> group=sortedEntries.get(j); if(h.bestNonHits.isEmpty()){ for(MassBank mb:group){ if(!h.hitsInDB.contains(mb)){ if(h.scoreBestNonHit==null)h.scoreBestNonHit=Double.NEGATIVE_INFINITY; h.bestNonHits.add(mb); h.scoreBestNonHit=Math.max(h.scoreBestNonHit,getSimilarityValue(i,massbankDB.indexOf(mb))); } } } int numberCorrectHits=0; for(MassBank mb:group){ if(h.hitsInDB.contains(mb)){ numberCorrectHits++; } } for(MassBank mbDB:h.hitsInDB){ if(group.contains(mbDB)){ h.minRankBestHit=Math.min(h.minRankBestHit,currentNumberHits+1); h.maxRankBestHit=Math.min(h.maxRankBestHit,currentNumberHits+1+(group.size()-numberCorrectHits)); h.scoreBestHit=Math.max(h.scoreBestHit, getSimilarityValue(i,massbankDB.indexOf(mbDB))); } } currentNumberHits+=group.size(); } } h.numberEntries=currentNumberHits; hs.hits.add(h); } return hs; } // public int[] getNumberOfHits(){ // int numberTrueHits=0; // int numberPossibleHits=0; // int numberNonemptyLists=0; // int[][] sortedIndizes=getIndizesOfSortedScores(); // for(int i=0;i<sortedIndizes.length;i++){ // boolean firstEntry=true; // boolean foundTrueHits=false; // boolean foundPossibleHits=false; // boolean foundNonempty=false; // for(int j=0;j<sortedIndizes[i].length;j++){ // int currCol=sortedIndizes[i][j]; // double currValue=getSimilarityValue(i,currCol); // if(Double.isNaN(currValue))continue; // if(massbankQuery.get(i).hasEqualInChiKey(massbankDB.get(currCol))){ // if(firstEntry)foundTrueHits=true; // foundPossibleHits=true; // } // double nextValue=j+1<sortedIndizes[i].length?getSimilarityValue(i,sortedIndizes[i][j+1]):Double.NaN; // if(!Double.isNaN(nextValue)&&currValue!=nextValue)firstEntry=false; // foundNonempty=true; // if(foundTrueHits&&foundPossibleHits&&foundNonempty)break; // } // if(foundTrueHits)numberTrueHits++; // if(foundPossibleHits)numberPossibleHits++; // if(foundNonempty)numberNonemptyLists++; // } // return new int[]{numberTrueHits, numberPossibleHits, numberNonemptyLists}; // } }
41,348
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
qValueSummaryMain.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/statistics/qValueSummaryMain.java
package de.unijena.bioinf.statistics; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; public class qValueSummaryMain { static File statisticsFolder=new File("D:\\metabo_tandem_ms\\MSBlast\\statistics\\posOld\\"); public static void main(String args[]) throws Exception{ List<String> comparisonMethods=new ArrayList<String>(); List<String> datasets=new ArrayList<String>(); for(File f:statisticsFolder.listFiles()){ if(f.isDirectory()){ comparisonMethods.add(f.getName()); for(File f2:f.listFiles()){ if(f2.getName().contains("qValuesComparisonMultiple")&&f2.getName().endsWith("txt")){ String dataset=f2.getName().replaceAll("qValuesComparisonMultiple_", "").replaceAll(".txt", ""); if(!datasets.contains(dataset))datasets.add(dataset); } } } } Collections.sort(comparisonMethods); Collections.sort(datasets); double[][] values=new double[comparisonMethods.size()][datasets.size()]; for(int i=0;i<values.length;i++){ for(int j=0;j<values[i].length;j++){ values[i][j]=Double.NaN; } } for(File f:statisticsFolder.listFiles()){ if(f.isDirectory()){ // System.out.println(f.getName()); int i=comparisonMethods.indexOf(f.getName()); for(File f2:f.listFiles()){ if(f2.getName().contains("qValuesComparisonMultiple")&&f2.getName().endsWith("txt")){ String dataset=f2.getName().replaceAll("qValuesComparisonMultiple_", "").replaceAll(".txt", ""); // System.out.println(dataset); int j=datasets.indexOf(dataset); double value=getAverageValue(f2); values[i][j]=value; } } } } Locale.setDefault(Locale.US); DecimalFormat df=new DecimalFormat("0.000000"); for(String d:datasets){ System.out.print("\t"+d); } System.out.println(); for(int i=0;i<values.length;i++){ System.out.print(comparisonMethods.get(i)); for(int j=0;j<values[i].length;j++){ System.out.print("\t"+df.format(values[i][j])); } System.out.println(); } } public static double getAverageValue(File f) throws Exception{ BufferedReader br=new BufferedReader(new FileReader(f)); String line=""; while((line=br.readLine())!=null){ if(line.startsWith("average sum")){ return Double.parseDouble(line.split("\t")[3]); } } return Double.NaN; } }
2,596
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MSBlastDecoyTrees.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/msblast/MSBlastDecoyTrees.java
package de.unijena.bioinf.msblast; //Generating Decoy DB import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.decoy.decoytrees.DecoySpectrum; import de.unijena.bioinf.decoy.model.decoytreeconstructors.ConditionalFastConstructor; import de.unijena.bioinf.decoy.model.decoytreeconstructors.DecoySpectrumConstructor; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.CHARGE; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.DATASET; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.METHOD; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.POSTPROCESS; public class MSBlastDecoyTrees { public static void main(String args[]) throws Exception{ Locale.setDefault(Locale.US); ParametersDecoySpectrumConstruction p=new ParametersDecoySpectrumConstruction(args); if(!p.isCorrectCombination()){ System.err.println("\""+Arrays.toString(args)+"\" is not a correct parameter combination."); return; } Map<File,Graph> origDBMap=p.getAllGraphsInOriginal(); Map<Integer,String> inchis=getInchiKeysByID(p.getInchiKeysFile()); p.getAllPeaksInOriginal(); BufferedWriter bw=null; if(p.rt){ File f=p.getOutputFileRunningTime(); if(!f.getParentFile().exists())f.getParentFile().mkdirs(); bw=new BufferedWriter(new FileWriter(f)); } int i=0; long allTimes=0; if(p.m == ParametersDecoySpectrumConstruction.METHOD.CONDITIONALFAST){ ConditionalFastConstructor.setM(p); } for(Entry<File,Graph> e:origDBMap.entrySet()){ i++; String name=e.getKey().getName().replaceAll(".dot","").replaceAll(".ms",""); System.out.println(i + " of "+origDBMap.size() +" processed ("+name+")"); // if(!name.equals("qpos559"))continue; int number=Integer.parseInt(name.replaceAll("\\D", "")); String inchi=inchis.get(number); String acc=p.getMassbankID(number); DecoySpectrum tree=null; DecoySpectrumConstructor dtc=p.getDecoyTreeConstructor(); dtc.setOriginalTree(e.getValue()); Graph tmpGraph=new Graph(e.getValue()); boolean foundDifferentTree=false; int n=0; long current=System.currentTimeMillis(); while(!foundDifferentTree&&n<100){ tree=dtc.getDecoySpectrum(); if(!tree.equalsGraph(tmpGraph)||p.m == ParametersDecoySpectrumConstruction.METHOD.ORIGINAL){ foundDifferentTree=true; }else{ // System.out.println("no different tree found, try again."); } n++; } long time=System.currentTimeMillis()-current; if(bw!=null){ bw.write("time for processing "+name +" (in milliseconds): "+time); bw.newLine(); } allTimes+=(time); if(!foundDifferentTree)System.err.println("no different tree found for "+p.getOutputFileDot(acc).getAbsolutePath()); // System.out.println(p.getOutputFileDot(acc).getAbsolutePath()); if(!p.pp.contains(POSTPROCESS.PPDiff)&&tree.getParent()!=null){ tree.writeAsDot(p.getOutputFileDot(acc)); } tree.writeAsMassbank(p.getOutputFolderMassbank(), tree.getPeaks(), tree.getParent(), 0, acc, acc+"_"+p.getInstrumentName(), p.getInstrumentName(), inchi, p.isPositive(),p.pp.contains(POSTPROCESS.PPDiff)); } if(bw!=null){ bw.write("time for processing all compounds (in milliseconds): "+ allTimes); bw.newLine(); bw.close(); } System.out.println(p.getDecoyTreeConstructor().getMethodNameLong()+" finished."); p.deleteAllGraphsInOriginalDB(); } public static Map<String,List<Integer>> getInchiKeysByInchi(File inchiKeysFile) throws Exception{ Map<String,List<Integer>> inchis=new HashMap<String,List<Integer>>(); BufferedReader br=new BufferedReader(new FileReader(inchiKeysFile)); String line=br.readLine(); List<String> header=Arrays.asList(line.split(",")); while((line=br.readLine())!=null){ String l[]=line.split("\",\""); int id=Integer.parseInt(l[header.indexOf("\"mid\"")].replaceAll("\"","")); String inchiTmp=l[header.indexOf("\"inchi\"")].replaceAll("\"","").replaceAll("\"",""); if(!inchiTmp.isEmpty()){ String inchi=inchiTmp.split("/")[1]+"/"+inchiTmp.split("/")[2]; if(!inchis.containsKey(inchi))inchis.put(inchi, new ArrayList<Integer>()); inchis.get(inchi).add(id); } } br.close(); return inchis; } public static Map<Integer,String> getInchiKeysByID(File inchiKeysFile) throws Exception{ Map<Integer,String> inchis=new HashMap<Integer,String>(); BufferedReader br=new BufferedReader(new FileReader(inchiKeysFile)); String line=br.readLine(); List<String> header=Arrays.asList(line.split("\t",Integer.MAX_VALUE)); while((line=br.readLine())!=null){ String l[]=line.replaceAll("\"","").split("\t",Integer.MAX_VALUE); if(l.length!=header.size())l=line.split(","); int id=Integer.parseInt(l[header.indexOf("id")]); String inchiTmp=l[header.indexOf("inchi")].replaceAll("\"",""); if(!inchiTmp.isEmpty()){ String[] isplit=inchiTmp.split("/"); if(isplit.length>=3&&!isplit[2].startsWith("c")){ System.out.print(inchiTmp); System.out.println(); } if(isplit.length>=4&&!isplit[3].startsWith("h")){ System.out.print(inchiTmp); System.out.println(); } String inchi=isplit[0]+"/"+isplit[1]+(isplit.length>=3&&(isplit[2].startsWith("c")||isplit[2].startsWith("h"))?("/"+isplit[2]):"")+(isplit.length>=4&&isplit[3].startsWith("h")?("/"+isplit[3]):""); inchis.put(id, inchi); } } br.close(); return inchis; } }
5,911
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
Main.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/msblast/Main.java
package de.unijena.bioinf.msblast; public class Main { public static void main(String args[]) throws Exception{ // for(String db:new String[]{"agilent","massbankorbi","massbankqtof","massbank"}){ // for(String d:new String[]{"Trees","Files"}){ // for(String method:new String[]{"Original"}){ // MSBlastDecoyTrees.main( // ("-base U:\\MSBlast\\Data\\ " // + "-c pos " // + "-db "+db+" " // + "-d "+d+" " // + "-method "+method+" " // + "-ppm 10 " // + "-ae 2").split(" ")); // } // } // } // for(int i=1;i<=10;i++){ // for(String db:new String[]{/*"agilent",*/"massbankorbi","massbankqtof"}){ // for(String d:new String[]{/*"Trees",*/"Files"}){ // for(String method:new String[]{"RandomPeaks","MixedSpectrum","ConditionalFast","Reroot","RandomTree"}){ // MSBlastDecoyTrees.main( // ("-base U:\\MSBlast\\Data\\ " // + "-c pos " // + "-db "+db+" " // + "-d "+d+" " // + "-method "+method+" " // + "-addFolder _"+i+" " // + "-ppm 10 " // + "-ae 2").split(" ")); // } // } // } // } for(int i=1;i<=1;i++){ for(String db:new String[]{"massbankqtof"}){ for(String d:new String[]{"Trees"}){ for(String method:new String[]{"Reroot"}){ MSBlastDecoyTrees.main( ("-base U:\\MSBlast\\Data\\ " + "-c pos " + "-db "+db+" " + "-d "+d+" " + "-method "+method+" " + "-addFolder _"+i+" " + "-ppm 10 " + "-ae 2").split(" ")); } } } } } }
1,754
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ParametersDecoySpectrumConstruction.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/msblast/ParametersDecoySpectrumConstruction.java
package de.unijena.bioinf.msblast; import java.io.File; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.decoy.model.decoytreeconstructors.ConditionalFastConstructor; import de.unijena.bioinf.decoy.model.decoytreeconstructors.ConditionalPeaksConstructor; import de.unijena.bioinf.decoy.model.decoytreeconstructors.DefaultDecoyFileConstructor; import de.unijena.bioinf.decoy.model.decoytreeconstructors.DefaultDecoyTreeConstructor; import de.unijena.bioinf.decoy.model.decoytreeconstructors.MixedSpectrumConstructor; import de.unijena.bioinf.decoy.model.decoytreeconstructors.RandomPeaksConstructor; import de.unijena.bioinf.decoy.model.decoytreeconstructors.RandomTreeDecoyTreeConstructor; import de.unijena.bioinf.decoy.model.decoytreeconstructors.RerootDecoyTreeConstructor; import de.unijena.bioinf.deocy.Utils; public class ParametersDecoySpectrumConstruction{ public static enum CHARGE{POS,NEG}; public static enum DATASET{AGILENT,METLIN,MASSBANKORBI,MASSBANKQTOF,MASSBANK,GNPS}; public static enum DATA{FILES,TREES}; public static enum METHOD{ORIGINAL, REROOT, RANDOMPEAKS, CONDITIONALPEAKS, CONDITIONALFAST, MIXEDSPECTRUM, RANDOMTREE}; public static enum POSTPROCESS{PPDiff}; static String sep=System.getProperty("file.separator"); static String baseOriginalFiles="OriginalFiles"; static String baseOriginalTrees="OriginalTrees"; static String baseDB="DataBases"; static String baseRT="RunningTimes"; static String dot="dot"; static String massbank="massbank"; static String ms="ms"; public String base; CHARGE c; DATASET ds; DATA d; METHOD m; List<POSTPROCESS> pp; public String addFolder=""; public boolean rt; public double ppm; public double ae; Map<File,Graph> allGraphsInOriginal; Map<File,List<double[]>> allPeaksInOriginal; DecimalFormat df=new DecimalFormat("000000"); public ParametersDecoySpectrumConstruction(String base, CHARGE c, DATASET ds, DATA d, METHOD m, List<POSTPROCESS> pp, double ppm, double ae){ this.base=base; this.c=c; this.ds=ds; this.d=d; this.m=m; this.pp=pp; this.ppm=ppm; this.ae=ae; } public ParametersDecoySpectrumConstruction(String[] args){ this.pp=new ArrayList<POSTPROCESS>(); int i=0; while(i<args.length){ if(args[i].equals("-base"))this.base=args[++i]; if(args[i].equals("-c")){ String charge=args[++i]; if(charge.equals("pos"))this.c=CHARGE.POS; if(charge.equals("neg"))this.c=CHARGE.NEG; } if(args[i].equals("-db")){ String db=args[++i]; if(db.equals("agilent"))this.ds=DATASET.AGILENT; if(db.equals("metlin"))this.ds=DATASET.METLIN; if(db.equals("massbankorbi"))this.ds=DATASET.MASSBANKORBI; if(db.equals("massbankqtof"))this.ds=DATASET.MASSBANKQTOF; if(db.equals("massbank"))this.ds=DATASET.MASSBANK; if(db.equals("gnps"))this.ds=DATASET.GNPS; } if(args[i].equals("-d")){ String data=args[++i]; for(DATA d:DATA.values()){ if(data.equals(getDataName(d)))this.d=d; } } if(args[i].equals("-method")){ String db=args[++i]; for(METHOD m:METHOD.values()){ if(db.equals(getDecoyTreeConstructorName(m)))this.m=m; } } if(args[i].equals("-addFolder"))this.addFolder=args[++i]; if(args[i].equals("-rt"))this.rt=true; if(args[i].equals("-ppm"))this.ppm=Double.parseDouble(args[++i]); if(args[i].equals("-ae"))this.ae=Double.parseDouble(args[++i]); if(args[i].equals("-postprocess")){ while(!args[i+1].startsWith("-")){ String post=args[++i]; if(post.equals("PPDiff"))this.pp.add(POSTPROCESS.PPDiff); } } i++; } } public boolean isCorrectCombination(){ if(d.equals(DATA.FILES)&&(m.equals(METHOD.REROOT)||m.equals(METHOD.RANDOMTREE)))return false; return true; } public ParametersDecoySpectrumConstruction(String base, CHARGE c, DATASET ds, DATA d, METHOD m, List<POSTPROCESS> pp, String addFolder, double ppm, double ae){ this(base, c, ds, d, m, pp, ppm, ae); this.addFolder=addFolder; } public Map<File,Graph> getAllGraphsInOriginal(){ if (allGraphsInOriginal==null){ allGraphsInOriginal=Utils.readGraphs(getFolderOriginalFiles()); } return allGraphsInOriginal; } public Map<File,List<double[]>> getAllPeaksInOriginal(){ if (allPeaksInOriginal==null){ allPeaksInOriginal=new HashMap<File,List<double[]>>(); Map<File,Graph> allGraphs=getAllGraphsInOriginal(); for(Entry<File,Graph> e:allGraphs.entrySet()){ DefaultDecoyTree dt=new DefaultDecoyTree(e.getValue()); List<double[]> r=new ArrayList<double[]>(); for(DecoyTreeVertex dv:dt.getVertices()){ r.add(new double[]{dv.mz,dv.intensity}); } allPeaksInOriginal.put(e.getKey(), r); } } return allPeaksInOriginal; } public void deleteAllGraphsInOriginalDB(){ if(allGraphsInOriginal!=null)allGraphsInOriginal.clear(); } public File getInchiKeysFile(){ return new File(base+sep+getDatasetLong()+".csv"); } public DefaultDecoyTreeConstructor getDecoyTreeConstructor(){ switch(m){ // case ORIGINALTREES: return new DefaultDecoyTreeConstructor(this); case ORIGINAL: return new DefaultDecoyTreeConstructor(this); case REROOT: return new RerootDecoyTreeConstructor(this); case RANDOMPEAKS: return new RandomPeaksConstructor(this); case CONDITIONALPEAKS: return new ConditionalPeaksConstructor(this); case CONDITIONALFAST: return new ConditionalFastConstructor(this); case MIXEDSPECTRUM: return new MixedSpectrumConstructor(this); case RANDOMTREE:return new RandomTreeDecoyTreeConstructor(this); default: return null; } } public String getDataName(){ return getDataName(d); } public static String getDataName(DATA d){ switch(d){ case FILES: return "Files"; case TREES: return "Trees"; default: return null; } } public static String getDecoyTreeConstructorName(METHOD m){ switch(m){ // case ORIGINALTREES: return DefaultDecoyTreeConstructor.methodNameLong; case ORIGINAL: return DefaultDecoyFileConstructor.methodNameLong; case REROOT: return RerootDecoyTreeConstructor.methodNameLong; case RANDOMPEAKS: return RandomPeaksConstructor.methodNameLong; case CONDITIONALPEAKS: return ConditionalPeaksConstructor.methodNameLong; case CONDITIONALFAST: return ConditionalFastConstructor.methodNameLong; case MIXEDSPECTRUM: return MixedSpectrumConstructor.methodNameLong; case RANDOMTREE: return RandomTreeDecoyTreeConstructor.methodNameLong; default: return null; } } public String getPostProcessNameLong(){ String result=""; if(pp.contains(POSTPROCESS.PPDiff))result+="PPDiff"; return result; } public String getChargePath(){ switch(c){ case POS:return "pos"; case NEG:return "neg"; default: return null; } } public String getChargeShort(){ switch(c){ case POS:return "P"; case NEG:return "N"; default: return null; } } public String getChargeLong(){ switch(c){ case POS:return "Positive"; case NEG:return "Negative"; default: return null; } } public String getDatasetLong(){ switch(ds){ case AGILENT:return "Agilent"; case METLIN:return "Metlin"; case MASSBANKORBI:return "MassbankOrbi"; case MASSBANKQTOF:return "MassbankQTof"; case MASSBANK:return "Massbank"; case GNPS:return "Gnps"; default: return null; } } public String getDatasetShort(){ switch(ds){ case AGILENT:return "A"; case METLIN:return "M"; case MASSBANKORBI:return "O"; case MASSBANKQTOF:return "Q"; case MASSBANK:return "B"; case GNPS:return "G"; default: return null; } } public File getOutputFolder(){ return new File(base+sep+baseDB+sep+getDatasetLong()+sep+getChargePath()+sep+getInstrumentName()); } public File getOutputFolderRunningTime(){ return new File(base+sep+baseRT+sep+getDatasetLong()+sep+getChargePath()+sep+getInstrumentName()); } public File getOutputFolderDot(){ return new File(getOutputFolder().getAbsolutePath()+sep+dot+addFolder); } public File getOutputFileRunningTime(){ return new File(getOutputFolderRunningTime().getAbsolutePath()+sep+"runningTime_"+getInstrumentName()+addFolder+".txt"); } public File getOutputFileDot(String fileName){ return new File(getOutputFolderDot().getAbsolutePath()+sep+fileName+".dot"); } public File getOutputFileMassbank(String fileName){ return new File(getOutputFolderMassbank().getAbsolutePath()+sep+fileName+".txt"); } public File getOutputFolderMassbank(){ return new File(getOutputFolder().getAbsolutePath()+sep+massbank+addFolder); } public File getFolderOriginalFiles(){ String baseOriginal=d.equals(DATA.TREES)?baseOriginalTrees:baseOriginalFiles; String folderOriginal=d.equals(DATA.TREES)?dot:ms; return new File(base+sep+baseOriginal+sep+getDatasetLong()+sep+getChargePath()+sep+folderOriginal); } public String getMethodNameLong(){ return getDataName()+getDecoyTreeConstructor().getMethodNameLong(); } public String getMassbankFirstID(){ return getDatasetShort()+getChargeShort()+getMethodNameLong()+getPostProcessNameLong(); } public String getMassbankID(int number){ return getMassbankFirstID()+df.format(number); } public String getInstrumentName(){ return getDatasetLong()+getChargeLong()+getMethodNameLong()+getPostProcessNameLong(); } public Boolean isPositive(){ switch(c){ case POS:return true; case NEG:return false; default: return null; } } public Double getMinMass(){ switch(ds){ case AGILENT:return 50.0; case METLIN:return 29.0; case MASSBANKORBI:return 29.0; case MASSBANKQTOF:return 40.0; case MASSBANK: return 29.0; case GNPS: return 50.0; default: return null; } } }
10,251
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ComparisonMethodOberacher.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ComparisonMethodOberacher.java
package de.unijena.bioinf.spectralcomparison; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; import de.unijena.bioinf.statistics.Result; public class ComparisonMethodOberacher implements ComparisonMethod{ static public final String methodNameLong="Oberacher"; ParametersSpectralComparison p; public List<MassBank> s1; public List<MassBank> s2; public ComparisonMethodOberacher(ParametersSpectralComparison p) { this.p=p; } public String getMethodNameLong(){ return methodNameLong; } public void setSpectra(List<MassBank> s1, List<MassBank> s2) { this.s1=s1; this.s2=s2; } public List<MassBank>[] getSpectra() { return new List[]{s1,s2}; } @Override public AlignmentMatrix getAlignmentMatrix() { Result[][] results=p.getPostProcess().getResultList(this); List<String> left=new ArrayList<String>(); for(MassBank m:s1)left.add(m.massbankID); List<String> right=new ArrayList<String>(); for(MassBank m:s2)right.add(m.massbankID); String queryFile=p.p1.getOutputFolderMassbank().getAbsolutePath(); String resultFile=p.p2.getOutputFolderMassbank().getAbsolutePath(); AlignmentMatrix matrix=new AlignmentMatrix(queryFile, resultFile, left, right, results); return matrix; } public Result getResult(List<double[]> peaksLeft, List<double[]> peaksRight){ int numberMatches=0; for(double[] peaks1:peaksLeft){ double[] bestMatchingPeak=null; double error=Utils.getAbsoluteErrorForMass(peaks1[0], p.ppm, p.ae); for(double[] peaks2:peaksRight){ double diff=Math.abs(peaks1[0]-peaks2[0]); if(diff<error&&(bestMatchingPeak==null||Math.abs(peaks1[0]-bestMatchingPeak[0])>diff)){ bestMatchingPeak=peaks2; } } if(bestMatchingPeak!=null){ numberMatches++; } } Result r=new Result(numberMatches, 1.0*Math.pow(numberMatches,2)/peaksLeft.size()/peaksRight.size()); return r; } public double[][] calculateFP(double [][] scores) { double[] means = new double[scores.length]; for (int i=0; i<scores.length; i++){ double sum =0; int n=0; for (int j=0; j<scores[i].length; j++){ if(!Double.isInfinite(scores[i][j])){ sum += scores[i][j]; n++; } } means[i] = sum/n; } double[][] correlationCoefficient = new double[scores.length][scores.length]; for (int i=0; i<correlationCoefficient.length; i++){ for (int j=0; j<correlationCoefficient.length; j++){ double combinedSum =0; double isum =0; double jsum=0; for (int k=0; k<correlationCoefficient[i].length; k++){ if(!Double.isInfinite(scores[i][k])&&!Double.isInfinite(scores[j][k])){ combinedSum += (scores[i][k]-means[i])*(scores[j][k]-means[j]); isum += Math.pow(scores[i][k]-means[i],2); jsum += Math.pow(scores[j][k]-means[j],2); } } correlationCoefficient[i][j]=combinedSum/(Math.pow(isum,0.5)*Math.pow(jsum,0.5)); } } return correlationCoefficient; } }
3,219
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
PostProcessMethodSimple.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/PostProcessMethodSimple.java
package de.unijena.bioinf.spectralcomparison; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.statistics.Result; public class PostProcessMethodSimple implements PostProcessMethod{ static public final String methodNameLong=""; ParametersSpectralComparison p; public String getMethodNameLong(){ return methodNameLong; } public PostProcessMethodSimple(ParametersSpectralComparison p){ this.p=p; } @Override public Result[][] getResultList(ComparisonMethod cm) { BufferedWriter bw=null; if(p.rt){ File f=p.getOutputFileRunningTime(); if(!f.getParentFile().exists())f.getParentFile().mkdirs(); try{ bw=new BufferedWriter(new FileWriter(f)); }catch(IOException e){ System.err.println("could not create output file for running times: "+f.getAbsolutePath()); } } List<MassBank>[] spectra=cm.getSpectra(); Result[][] results=new Result[spectra[0].size()][spectra[1].size()]; long allTimes=0; for(int i=0;i<results.length;i++){ long current=System.currentTimeMillis(); for(int j=0;j<results[i].length;j++){ results[i][j]=cm.getResult(spectra[0].get(i).peaks, spectra[1].get(j).peaks); } long time=System.currentTimeMillis()-current; allTimes+=time; if(bw!=null){ try{ bw.write("time for processing "+spectra[0].get(i).massbankID+" (in milliseconds): "+time); bw.newLine(); }catch(IOException e){ System.err.println("could not write to output file for running times"); } } } if(bw!=null){ try{ bw.write("time for processing all compounds (in milliseconds): "+ allTimes); bw.newLine(); bw.close(); }catch(IOException e){ System.err.println("could not close output file for running times"); } } return results; } }
2,006
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
AlignmentMatrix.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/AlignmentMatrix.java
package de.unijena.bioinf.spectralcomparison; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Arrays; import java.util.List; import de.unijena.bioinf.statistics.Result; public class AlignmentMatrix { String queryFile; String resultFile; List<String> left; List<String> right; Result[][] results; public AlignmentMatrix(String queryFile, String resultFile, List<String> leftEntries, List<String> rightEntries, Result[][] results){ this.queryFile=queryFile; this.resultFile=resultFile; this.left=leftEntries; this.right=rightEntries; this.results=results; } public void writeToCSV(File outputFile) throws Exception{ if(!outputFile.getParentFile().exists())outputFile.getParentFile().mkdirs(); BufferedWriter bw=new BufferedWriter(new FileWriter(outputFile)); bw.write("Query: "+queryFile+";"); bw.newLine(); bw.write("DB: "+resultFile+";"); bw.newLine(); bw.newLine(); for(String s:right)bw.write(","+s); bw.newLine(); for(int i=0;i<left.size();i++){ bw.write(left.get(i)); for(Result r:results[i]){ bw.write(","+r.score+" "+r.matchedPeaks); } bw.newLine(); } bw.close(); } }
1,242
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ComparisonMethodTreeAlignment.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ComparisonMethodTreeAlignment.java
package de.unijena.bioinf.spectralcomparison; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; import de.unijena.bioinf.statistics.Result; public class ComparisonMethodTreeAlignment implements ComparisonMethod{ static public final String methodNameLong="TreeAlignment"; ParametersSpectralComparison p; public List<MassBank> s1; public List<MassBank> s2; public ComparisonMethodTreeAlignment(ParametersSpectralComparison p) { this.p=p; } public String getMethodNameLong(){ return methodNameLong; } public void setSpectra(List<MassBank> s1, List<MassBank> s2) { this.s1=s1; this.s2=s2; } public List<MassBank>[] getSpectra() { return new List[]{s1,s2}; } @Override public AlignmentMatrix getAlignmentMatrix() { if(!p.getOutputFileComparison().getParentFile().exists())p.getOutputFileComparison().getParentFile().mkdirs(); String s1="-z -x -j " + "-m "+p.getOutputFileComparison()+" " + "--align "+p.p1.getOutputFolderDot()+" " + "--with "+p.p2.getOutputFolderDot(); String[] args=s1.split(" "); new de.unijena.bioinf.ftalign.Main().run(args); try{ String queryFile=p.p1.getOutputFolderMassbank().getAbsolutePath(); String resultFile=p.p2.getOutputFolderMassbank().getAbsolutePath(); BufferedReader br=new BufferedReader(new FileReader(p.getOutputFileComparison())); List<String> left=new ArrayList<String>(); List<String> right=new ArrayList<String>(); String[] l=br.readLine().split(","); for(int i=1;i<l.length;i++)right.add(l[i].replaceAll("\"","")); String line; while((line=br.readLine())!=null){ left.add(line.split(",")[0].replaceAll("\"","")); } br.close(); Result results[][]=new Result[left.size()][right.size()]; br=new BufferedReader(new FileReader(p.getOutputFileComparison())); line=br.readLine(); int i=0; while((line=br.readLine())!=null){ l=line.split(","); for(int j=1;j<l.length;j++){ results[i][j-1]=new Result(0,Double.parseDouble(l[j])); } i++; } br.close(); return new AlignmentMatrix(queryFile, resultFile, left, right, results); }catch(IOException e){ System.err.println(e); } return null; } public Result getResult(List<double[]> peaksLeft, List<double[]> peaksRight){ double cos=0; double length1=0; double length2=0; int numberMatches=0; double maxLeft=0; for(double[] p:peaksLeft)maxLeft=Math.max(maxLeft, p[1]); double maxRight=0; for(double[] p:peaksRight)maxRight=Math.max(maxRight, p[1]); List<double[]> p1=new ArrayList<double[]>(); for(double[] p:peaksLeft){ // if(1000*p[1]/maxLeft>=5) p1.add(new double[]{p[0],Math.pow(1000*p[1]/maxLeft,0.5)*p[0]/10}); } List<double[]> p2=new ArrayList<double[]>(); for(double[] p:peaksRight){ // if(1000*p[1]/maxRight>=5) p2.add(new double[]{p[0],Math.pow(1000*p[1]/maxRight,0.5)*p[0]/10}); } for(double[] p:p1)length1+=Math.pow(p[1],2); for(double[] p:p2)length2+=Math.pow(p[1],2); for(double[] peaks1:p1){ double[] bestMatchingPeak=null; double error=Utils.getAbsoluteErrorForMass(peaks1[0], p.ppm, p.ae); for(double[] peaks2:p2){ double diff=Math.abs(peaks1[0]-peaks2[0]); if(diff<error&&(bestMatchingPeak==null||peaks1[1]>bestMatchingPeak[1])){ bestMatchingPeak=peaks2; } } if(bestMatchingPeak!=null){ cos+=peaks1[1]*bestMatchingPeak[1]; numberMatches++; } } Result r=new Result(numberMatches, cos/Math.pow(length1,0.5)/Math.pow(length2,0.5)); return r; } public double[][] calculateFP(double [][] scores) { double[] means = new double[scores.length]; for (int i=0; i<scores.length; i++){ double sum =0; int n=0; for (int j=0; j<scores[i].length; j++){ if(!Double.isInfinite(scores[i][j])){ sum += scores[i][j]; n++; } } means[i] = sum/n; } double[][] correlationCoefficient = new double[scores.length][scores.length]; for (int i=0; i<correlationCoefficient.length; i++){ for (int j=0; j<correlationCoefficient.length; j++){ double combinedSum =0; double isum =0; double jsum=0; for (int k=0; k<correlationCoefficient[i].length; k++){ if(!Double.isInfinite(scores[i][k])&&!Double.isInfinite(scores[j][k])){ combinedSum += (scores[i][k]-means[i])*(scores[j][k]-means[j]); isum += Math.pow(scores[i][k]-means[i],2); jsum += Math.pow(scores[j][k]-means[j],2); } } correlationCoefficient[i][j]=combinedSum/(Math.pow(isum,0.5)*Math.pow(jsum,0.5)); } } return correlationCoefficient; } }
5,059
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ComparisonMethodCosineDistance.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ComparisonMethodCosineDistance.java
package de.unijena.bioinf.spectralcomparison; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; import de.unijena.bioinf.statistics.Result; public class ComparisonMethodCosineDistance implements ComparisonMethod{ static public final String methodNameLong="CosineDistance"; ParametersSpectralComparison p; public List<MassBank> s1; public List<MassBank> s2; public ComparisonMethodCosineDistance(ParametersSpectralComparison p) { this.p=p; } public String getMethodNameLong(){ return methodNameLong; } public void setSpectra(List<MassBank> s1, List<MassBank> s2) { this.s1=s1; this.s2=s2; } public List<MassBank>[] getSpectra() { return new List[]{s1,s2}; } @Override public AlignmentMatrix getAlignmentMatrix() { Result[][] results=p.getPostProcess().getResultList(this); List<String> left=new ArrayList<String>(); for(MassBank m:s1)left.add(m.massbankID); List<String> right=new ArrayList<String>(); for(MassBank m:s2)right.add(m.massbankID); String queryFile=p.p1.getOutputFolderMassbank().getAbsolutePath(); String resultFile=p.p2.getOutputFolderMassbank().getAbsolutePath(); AlignmentMatrix matrix=new AlignmentMatrix(queryFile, resultFile, left, right, results); return matrix; } public Result getResult(List<double[]> peaksLeft, List<double[]> peaksRight){ double cos=0; double length1=0; double length2=0; int numberMatches=0; double maxLeft=0; for(double[] p:peaksLeft)maxLeft=Math.max(maxLeft, p[1]); double maxRight=0; for(double[] p:peaksRight)maxRight=Math.max(maxRight, p[1]); List<double[]> p1=new ArrayList<double[]>(); for(double[] p:peaksLeft){ p1.add(new double[]{p[0],p[1]/maxLeft}); } List<double[]> p2=new ArrayList<double[]>(); for(double[] p:peaksRight){ p2.add(new double[]{p[0],p[1]/maxRight}); } for(double[] p:p1)length1+=Math.pow(p[1],2); for(double[] p:p2)length2+=Math.pow(p[1],2); for(double[] peaks1:p1){ double[] bestMatchingPeak=null; double error=Utils.getAbsoluteErrorForMass(peaks1[0], p.ppm, p.ae); for(double[] peaks2:p2){ double diff=Math.abs(peaks1[0]-peaks2[0]); if(diff<error&&(bestMatchingPeak==null||peaks1[1]>bestMatchingPeak[1])){ bestMatchingPeak=peaks2; } } if(bestMatchingPeak!=null){ cos+=peaks1[1]*bestMatchingPeak[1]; numberMatches++; } } Result r=new Result(numberMatches, cos/Math.pow(length1,0.5)/Math.pow(length2,0.5)); return r; } public double[][] calculateFP(double [][] scores) { double[] means = new double[scores.length]; for (int i=0; i<scores.length; i++){ double sum =0; int n=0; for (int j=0; j<scores[i].length; j++){ if(!Double.isInfinite(scores[i][j])){ sum += scores[i][j]; n++; } } means[i] = sum/n; } double[][] correlationCoefficient = new double[scores.length][scores.length]; for (int i=0; i<correlationCoefficient.length; i++){ for (int j=0; j<correlationCoefficient.length; j++){ double combinedSum =0; double isum =0; double jsum=0; for (int k=0; k<correlationCoefficient[i].length; k++){ if(!Double.isInfinite(scores[i][k])&&!Double.isInfinite(scores[j][k])){ combinedSum += (scores[i][k]-means[i])*(scores[j][k]-means[j]); isum += Math.pow(scores[i][k]-means[i],2); jsum += Math.pow(scores[j][k]-means[j],2); } } correlationCoefficient[i][j]=combinedSum/(Math.pow(isum,0.5)*Math.pow(jsum,0.5)); } } return correlationCoefficient; } }
3,826
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
Main.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/Main.java
package de.unijena.bioinf.spectralcomparison; public class Main { public static void main(String args[]) throws Exception{ for (String db1:new String[]{"massbankorbi","massbankqtof","agilent"}){ for (String db2:new String[]{"massbankorbi","massbankqtof","agilent"}){ if(db1.equals(db2))continue; for (String methodSearch:new String[]{/*"CosineDistance","MassBank", "OberacherWithIntensities","OberacherWithIntensitiesAndMasses", */"TreeAlignment"}){ for (String d1:new String[]{"Trees"/*, "Files"*/}){ for (String d2:new String[]{"Trees"/*, "Files"*/}){ for (String methodDecoy:new String[]{"Original"}){ MSBlastSpectralComparison.main( ("-base U:\\MSBlast\\searchResults\\ " + "-method "+methodSearch+" " + "-ppm 10 " + "-ae 2 " + "-postprocess Simple " + "-ds1 " +"-base U:\\MSBlast\\Data\\ " + "-c pos " + "-db "+db1+" " + "-d "+d1+" " + "-method Original " + "-ppm 10 " + "-ae 2 " + "-ds2 " + "-base U:\\MSBlast\\Data\\ " + "-c pos " + "-db "+db2+" " + "-d "+d2+" " + "-method "+methodDecoy+" " + "-ppm 10 " + "-ae 2").split(" ")); } } } } } } } }
1,379
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ComparisonMethodMassBank.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ComparisonMethodMassBank.java
package de.unijena.bioinf.spectralcomparison; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; import de.unijena.bioinf.statistics.Result; public class ComparisonMethodMassBank implements ComparisonMethod{ static public final String methodNameLong="MassBank"; ParametersSpectralComparison p; public List<MassBank> s1; public List<MassBank> s2; public ComparisonMethodMassBank(ParametersSpectralComparison p) { this.p=p; } public String getMethodNameLong(){ return methodNameLong; } public void setSpectra(List<MassBank> s1, List<MassBank> s2) { this.s1=s1; this.s2=s2; } public List<MassBank>[] getSpectra() { return new List[]{s1,s2}; } @Override public AlignmentMatrix getAlignmentMatrix() { Result[][] results=p.getPostProcess().getResultList(this); List<String> left=new ArrayList<String>(); for(MassBank m:s1)left.add(m.massbankID); List<String> right=new ArrayList<String>(); for(MassBank m:s2)right.add(m.massbankID); String queryFile=p.p1.getOutputFolderMassbank().getAbsolutePath(); String resultFile=p.p2.getOutputFolderMassbank().getAbsolutePath(); AlignmentMatrix matrix=new AlignmentMatrix(queryFile, resultFile, left, right, results); return matrix; } public Result getResult(List<double[]> peaksLeft, List<double[]> peaksRight){ double cos=0; double length1=0; double length2=0; int numberMatches=0; double maxLeft=0; for(double[] p:peaksLeft)maxLeft=Math.max(maxLeft, p[1]); double maxRight=0; for(double[] p:peaksRight)maxRight=Math.max(maxRight, p[1]); List<double[]> p1=new ArrayList<double[]>(); for(double[] p:peaksLeft){ // if(1000*p[1]/maxLeft>=5) p1.add(new double[]{p[0],Math.pow(1000*p[1]/maxLeft,0.5)*p[0]/10}); } List<double[]> p2=new ArrayList<double[]>(); for(double[] p:peaksRight){ // if(1000*p[1]/maxRight>=5) p2.add(new double[]{p[0],Math.pow(1000*p[1]/maxRight,0.5)*p[0]/10}); } for(double[] p:p1)length1+=Math.pow(p[1],2); for(double[] p:p2)length2+=Math.pow(p[1],2); for(double[] peaks1:p1){ double[] bestMatchingPeak=null; double error=Utils.getAbsoluteErrorForMass(peaks1[0], p.ppm, p.ae); for(double[] peaks2:p2){ double diff=Math.abs(peaks1[0]-peaks2[0]); if(diff<error&&(bestMatchingPeak==null||peaks1[1]>bestMatchingPeak[1])){ bestMatchingPeak=peaks2; } } if(bestMatchingPeak!=null){ cos+=peaks1[1]*bestMatchingPeak[1]; numberMatches++; } } Result r=new Result(numberMatches, cos/Math.pow(length1,0.5)/Math.pow(length2,0.5)); return r; } public double[][] calculateFP(double [][] scores) { double[] means = new double[scores.length]; for (int i=0; i<scores.length; i++){ double sum =0; int n=0; for (int j=0; j<scores[i].length; j++){ if(!Double.isInfinite(scores[i][j])){ sum += scores[i][j]; n++; } } means[i] = sum/n; } double[][] correlationCoefficient = new double[scores.length][scores.length]; for (int i=0; i<correlationCoefficient.length; i++){ for (int j=0; j<correlationCoefficient.length; j++){ double combinedSum =0; double isum =0; double jsum=0; for (int k=0; k<correlationCoefficient[i].length; k++){ if(!Double.isInfinite(scores[i][k])&&!Double.isInfinite(scores[j][k])){ combinedSum += (scores[i][k]-means[i])*(scores[j][k]-means[j]); isum += Math.pow(scores[i][k]-means[i],2); jsum += Math.pow(scores[j][k]-means[j],2); } } correlationCoefficient[i][j]=combinedSum/(Math.pow(isum,0.5)*Math.pow(jsum,0.5)); } } return correlationCoefficient; } }
3,927
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ComparisonMethodMassBankEffectivePeaks.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ComparisonMethodMassBankEffectivePeaks.java
package de.unijena.bioinf.spectralcomparison; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; import de.unijena.bioinf.statistics.Result; public class ComparisonMethodMassBankEffectivePeaks implements ComparisonMethod{ static public final String methodNameLong="MassBankEffectivePeaks"; ParametersSpectralComparison p; public List<MassBank> s1; public List<MassBank> s2; public ComparisonMethodMassBankEffectivePeaks(ParametersSpectralComparison p) { this.p=p; } public String getMethodNameLong(){ return methodNameLong; } public void setSpectra(List<MassBank> s1, List<MassBank> s2) { this.s1=s1; this.s2=s2; } public List<MassBank>[] getSpectra() { return new List[]{s1,s2}; } @Override public AlignmentMatrix getAlignmentMatrix() { Result[][] results=p.getPostProcess().getResultList(this); List<String> left=new ArrayList<String>(); for(MassBank m:s1)left.add(m.massbankID); List<String> right=new ArrayList<String>(); for(MassBank m:s2)right.add(m.massbankID); String queryFile=p.p1.getOutputFolderMassbank().getAbsolutePath(); String resultFile=p.p2.getOutputFolderMassbank().getAbsolutePath(); AlignmentMatrix matrix=new AlignmentMatrix(queryFile, resultFile, left, right, results); return matrix; } public Result getResult(List<double[]> peaksLeft, List<double[]> peaksRight){ double cos=0; double length1=0; double length2=0; int numberMatches=0; int numberEffectivePeaksQuery=0; int numberEffectiveMatchesQuery=0; double maxLeft=0; for(double[] p:peaksLeft)maxLeft=Math.max(maxLeft, p[1]); double maxRight=0; for(double[] p:peaksRight)maxRight=Math.max(maxRight, p[1]); List<double[]> p1=new ArrayList<double[]>(); List<Boolean> isEffectivePeakQuery=new ArrayList<Boolean>(); for(double[] p:peaksLeft){ isEffectivePeakQuery.add(1000*p[1]/maxLeft>=5&&p[0]<1000); p1.add(new double[]{p[0],Math.pow(1000*p[1]/maxLeft,0.5)*p[0]/10}); } List<double[]> p2=new ArrayList<double[]>(); for(double[] p:peaksRight)p2.add(new double[]{p[0],Math.pow(1000*p[1]/maxRight,0.5)*p[0]/10}); for(double[] p:p1)length1+=Math.pow(p[1],2); for(double[] p:p2)length2+=Math.pow(p[1],2); for(int i=0;i<p1.size();i++){ double[] peaks1=p1.get(i); double[] bestMatchingPeak=null; double error=Utils.getAbsoluteErrorForMass(peaks1[0], p.ppm, p.ae); for(double[] peaks2:p2){ double diff=Math.abs(peaks1[0]-peaks2[0]); if(diff<error&&(bestMatchingPeak==null||peaks1[1]>bestMatchingPeak[1])){ bestMatchingPeak=peaks2; } } if(bestMatchingPeak!=null){ if(isEffectivePeakQuery.get(i))numberEffectiveMatchesQuery++; cos+=peaks1[1]*bestMatchingPeak[1]; numberMatches++; } } for(Boolean b:isEffectivePeakQuery)if(b)numberEffectivePeaksQuery++; if((numberEffectivePeaksQuery>=3&&numberMatches<3)||(numberEffectivePeaksQuery<3&&numberEffectivePeaksQuery!=numberEffectiveMatchesQuery)){ numberMatches=0; cos=0; } Result r=new Result(numberMatches, cos/Math.pow(length1,0.5)/Math.pow(length2,0.5)); return r; } public double[][] calculateFP(double [][] scores) { double[] means = new double[scores.length]; for (int i=0; i<scores.length; i++){ double sum =0; int n=0; for (int j=0; j<scores[i].length; j++){ if(!Double.isInfinite(scores[i][j])){ sum += scores[i][j]; n++; } } means[i] = sum/n; } double[][] correlationCoefficient = new double[scores.length][scores.length]; for (int i=0; i<correlationCoefficient.length; i++){ for (int j=0; j<correlationCoefficient.length; j++){ double combinedSum =0; double isum =0; double jsum=0; for (int k=0; k<correlationCoefficient[i].length; k++){ if(!Double.isInfinite(scores[i][k])&&!Double.isInfinite(scores[j][k])){ combinedSum += (scores[i][k]-means[i])*(scores[j][k]-means[j]); isum += Math.pow(scores[i][k]-means[i],2); jsum += Math.pow(scores[j][k]-means[j],2); } } correlationCoefficient[i][j]=combinedSum/(Math.pow(isum,0.5)*Math.pow(jsum,0.5)); } } return correlationCoefficient; } }
4,457
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
PostProcessMethodPValue.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/PostProcessMethodPValue.java
package de.unijena.bioinf.spectralcomparison; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.TreeMap; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; import de.unijena.bioinf.pvalue.SisterSpectrumGeneratorConditionalPeaks; import de.unijena.bioinf.pvalue.SisterSpectrumGeneratorRandomPeaks; import de.unijena.bioinf.statistics.Result; public class PostProcessMethodPValue implements PostProcessMethod{ static public final String methodNameLong="PValue"; ParametersSpectralComparison p; Random r=new Random(); SisterSpectrumGeneratorRandomPeaks g; TreeMap<Double, Double> oversampling; TreeMap<Double, Integer> resultingDistribution; int z; int N=100000; double step=0.1; public String getMethodNameLong(){ return methodNameLong; } public PostProcessMethodPValue(ParametersSpectralComparison p){ this.p=p; } @Override public Result[][] getResultList(ComparisonMethod cm) { List<MassBank>[] spectra=cm.getSpectra(); Result[][] results=new Result[spectra[0].size()][spectra[1].size()]; for(int i=0;i<results.length;i++){ List<Double> tmp=new ArrayList<Double>(); for(int j=0;j<results[i].length;j++){ results[i][j]=cm.getResult(spectra[0].get(i).peaks, spectra[1].get(j).peaks); tmp.add(results[i][j].score); } if(spectra[0].get(i).massbankID.equals("MPOriginal001292")){ Collections.sort(tmp, Collections.reverseOrder()); for(double d:tmp)System.out.println(d); getPValues(spectra[0].get(i).peaks, p.p2, cm); } } return results; } public void getPValues(List<double[]> originalSpectrum,ParametersDecoySpectrumConstruction p, ComparisonMethod cm){ oversampling=new TreeMap<Double,Double>(); resultingDistribution=new TreeMap<Double,Integer>(); for(double i=0;i<=1;i+=step)oversampling.put(i,1.0); g=new SisterSpectrumGeneratorRandomPeaks(originalSpectrum.size(), p); List<double[]> startSpectrum=g.getStartSpectrum(); System.out.println(cm.getResult(originalSpectrum, startSpectrum).score); try{ BufferedWriter bwP=new BufferedWriter(new FileWriter(new File("U:\\MSBlast\\TrajectorySplittingP.txt"))); BufferedWriter bwMy=new BufferedWriter(new FileWriter(new File("U:\\MSBlast\\TrajectorySplittingMy.txt"))); BufferedWriter bwN=new BufferedWriter(new FileWriter(new File("U:\\MSBlast\\TrajectorySplittingN.txt"))); for(int test=0;test<100;test++){ z=0; double minOversampling=Double.MAX_VALUE; for(double d:oversampling.values())minOversampling=Math.min(minOversampling, d); simulateDPRTrajectory(startSpectrum, originalSpectrum, cm, minOversampling, 1); int n=0; double sum=0; for(Entry<Double, Double> e:oversampling.entrySet()){ if(!resultingDistribution.containsKey(e.getKey()))resultingDistribution.put(e.getKey(), 0); resultingDistribution.put(e.getKey(), resultingDistribution.get(e.getKey())+1); bwN.write(e.getKey()+" "+resultingDistribution.get(e.getKey())+"\n"); } for(Entry<Double, Integer> e:resultingDistribution.entrySet()){ n+=e.getValue(); sum+=e.getValue()/oversampling.get(e.getKey()); } for(double i:oversampling.keySet()){ bwP.write(i+" "+resultingDistribution.get(i)/oversampling.get(i)/sum+"\n"); bwMy.write(i+" "+sum*oversampling.get(i)/resultingDistribution.get(i)+"\n"); oversampling.put(i,sum*oversampling.get(i)/resultingDistribution.get(i)); } bwN.write(n+"\n"); bwN.write("\n"); bwN.flush(); bwP.write(sum+"\n"); bwP.write("\n"); bwP.flush(); bwMy.write("\n"); bwMy.flush(); resultingDistribution.clear(); System.out.println(test+". done!"); } bwN.close(); bwP.close(); bwMy.close(); }catch(Exception e){ System.err.println(e); } } public void simulateDPRTrajectory(List<double[]> decoySpectrum, List<double[]> originalSpectrum, ComparisonMethod cm, double omega, int level){ while(z<N){ List<double[]> sisterSpectrum=g.getSisterSpectrum(decoySpectrum); double oversamplingFactorOriginal=getOversamplingFactor(cm.getResult(originalSpectrum, decoySpectrum).score); double scoreSisterSpectrum=cm.getResult(originalSpectrum, sisterSpectrum).score; double oversamplingFactorSister=getOversamplingFactor(scoreSisterSpectrum); if(oversamplingFactorSister<omega)return; if(oversamplingFactorSister>oversamplingFactorOriginal){ double y=oversamplingFactorSister/oversamplingFactorOriginal; double remaining=oversamplingFactorSister%oversamplingFactorOriginal; double rand=r.nextDouble(); double yInt=Math.floor(y); if(rand<remaining)yInt=Math.floor(y)+1; for(long i=0;i<yInt;i++){ rand=r.nextDouble(); double newOmega=oversamplingFactorOriginal+rand*(oversamplingFactorSister-oversamplingFactorOriginal); simulateDPRTrajectory(sisterSpectrum, originalSpectrum, cm, newOmega, level++); } } double group=getOversamplingKey(scoreSisterSpectrum); if(!resultingDistribution.containsKey(group))resultingDistribution.put(group, 0); resultingDistribution.put(group, resultingDistribution.get(group)+1); System.out.println(z); z++; } } public double getOversamplingFactor(double score){ double oversamplingKey=getOversamplingKey(score); return oversampling.get(oversamplingKey); } public double getOversamplingKey(double score){ double overSamplingFactorCeiling=oversampling.ceilingKey(score); double overSamplingFactorFloor=oversampling.floorKey(score); return Math.abs(score-overSamplingFactorCeiling)<Math.abs(score-overSamplingFactorFloor)?overSamplingFactorCeiling:overSamplingFactorFloor; } }
6,110
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ComparisonMethodOberacherWithIntensities.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ComparisonMethodOberacherWithIntensities.java
package de.unijena.bioinf.spectralcomparison; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; import de.unijena.bioinf.statistics.Result; public class ComparisonMethodOberacherWithIntensities implements ComparisonMethod{ static public final String methodNameLong="OberacherWithIntensities"; ParametersSpectralComparison p; public List<MassBank> s1; public List<MassBank> s2; public ComparisonMethodOberacherWithIntensities(ParametersSpectralComparison p) { this.p=p; } public String getMethodNameLong(){ return methodNameLong; } public void setSpectra(List<MassBank> s1, List<MassBank> s2) { this.s1=s1; this.s2=s2; } public List<MassBank>[] getSpectra() { return new List[]{s1,s2}; } @Override public AlignmentMatrix getAlignmentMatrix() { Result[][] results=p.getPostProcess().getResultList(this); List<String> left=new ArrayList<String>(); for(MassBank m:s1)left.add(m.massbankID); List<String> right=new ArrayList<String>(); for(MassBank m:s2)right.add(m.massbankID); String queryFile=p.p1.getOutputFolderMassbank().getAbsolutePath(); String resultFile=p.p2.getOutputFolderMassbank().getAbsolutePath(); AlignmentMatrix matrix=new AlignmentMatrix(queryFile, resultFile, left, right, results); return matrix; } public Result getResult(List<double[]> peaksLeft, List<double[]> peaksRight){ int numberMatches=0; double intensityDiff=0; double maxLeft=0; for(double[] p:peaksLeft)maxLeft=Math.max(maxLeft, p[1]); double maxRight=0; for(double[] p:peaksRight)maxRight=Math.max(maxRight, p[1]); List<double[]> p1=new ArrayList<double[]>(); for(double[] p:peaksLeft)p1.add(new double[]{p[0], p[1]/maxLeft*100}); List<double[]> p2=new ArrayList<double[]>(); for(double[] p:peaksRight)p2.add(new double[]{p[0], p[1]/maxRight*100}); for(double[] peaks1:p1){ double[] bestMatchingPeak=null; double error=Utils.getAbsoluteErrorForMass(peaks1[0], p.ppm, p.ae); for(double[] peaks2:p2){ double diff=Math.abs(peaks1[0]-peaks2[0]); if(diff<error&&(bestMatchingPeak==null||Math.abs(peaks1[0]-bestMatchingPeak[0])>diff)){ bestMatchingPeak=peaks2; } } if(bestMatchingPeak!=null){ numberMatches++; intensityDiff+=Math.abs(peaks1[1]-bestMatchingPeak[1]); } } Result r=new Result(numberMatches, numberMatches!=0?1.0*Math.pow(numberMatches,4)/p1.size()/p2.size()/Math.pow(intensityDiff,0.25):0); return r; } public double[][] calculateFP(double [][] scores) { double[] means = new double[scores.length]; for (int i=0; i<scores.length; i++){ double sum =0; int n=0; for (int j=0; j<scores[i].length; j++){ if(!Double.isInfinite(scores[i][j])){ sum += scores[i][j]; n++; } } means[i] = sum/n; } double[][] correlationCoefficient = new double[scores.length][scores.length]; for (int i=0; i<correlationCoefficient.length; i++){ for (int j=0; j<correlationCoefficient.length; j++){ double combinedSum =0; double isum =0; double jsum=0; for (int k=0; k<correlationCoefficient[i].length; k++){ if(!Double.isInfinite(scores[i][k])&&!Double.isInfinite(scores[j][k])){ combinedSum += (scores[i][k]-means[i])*(scores[j][k]-means[j]); isum += Math.pow(scores[i][k]-means[i],2); jsum += Math.pow(scores[j][k]-means[j],2); } } correlationCoefficient[i][j]=combinedSum/(Math.pow(isum,0.5)*Math.pow(jsum,0.5)); } } return correlationCoefficient; } }
3,790
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ComparisonMethodOberacherPeakcounting.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ComparisonMethodOberacherPeakcounting.java
package de.unijena.bioinf.spectralcomparison; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; import de.unijena.bioinf.statistics.Result; public class ComparisonMethodOberacherPeakcounting implements ComparisonMethod{ static public final String methodNameLong="OberacherPeakcounting"; ParametersSpectralComparison p; public List<MassBank> s1; public List<MassBank> s2; public ComparisonMethodOberacherPeakcounting(ParametersSpectralComparison p) { this.p=p; } public String getMethodNameLong(){ return methodNameLong; } public void setSpectra(List<MassBank> s1, List<MassBank> s2) { this.s1=s1; this.s2=s2; } public List<MassBank>[] getSpectra() { return new List[]{s1,s2}; } @Override public AlignmentMatrix getAlignmentMatrix() { Result[][] results=p.getPostProcess().getResultList(this); List<String> left=new ArrayList<String>(); for(MassBank m:s1)left.add(m.massbankID); List<String> right=new ArrayList<String>(); for(MassBank m:s2)right.add(m.massbankID); String queryFile=p.p1.getOutputFolderMassbank().getAbsolutePath(); String resultFile=p.p2.getOutputFolderMassbank().getAbsolutePath(); AlignmentMatrix matrix=new AlignmentMatrix(queryFile, resultFile, left, right, results); return matrix; } public Result getResult(List<double[]> peaksLeft, List<double[]> peaksRight){ int numberMatches=0; for(double[] peaks1:peaksLeft){ double[] bestMatchingPeak=null; double error=Utils.getAbsoluteErrorForMass(peaks1[0], p.ppm, p.ae); for(double[] peaks2:peaksRight){ double diff=Math.abs(peaks1[0]-peaks2[0]); if(diff<error&&(bestMatchingPeak==null||Math.abs(peaks1[0]-bestMatchingPeak[0])>diff)){ bestMatchingPeak=peaks2; } } if(bestMatchingPeak!=null){ numberMatches++; } } Result r=new Result(numberMatches, 2.0*numberMatches/(peaksLeft.size()+peaksRight.size())); return r; } public double[][] calculateFP(double [][] scores) { double[] means = new double[scores.length]; for (int i=0; i<scores.length; i++){ double sum =0; int n=0; for (int j=0; j<scores[i].length; j++){ if(!Double.isInfinite(scores[i][j])){ sum += scores[i][j]; n++; } } means[i] = sum/n; } double[][] correlationCoefficient = new double[scores.length][scores.length]; for (int i=0; i<correlationCoefficient.length; i++){ for (int j=0; j<correlationCoefficient.length; j++){ double combinedSum =0; double isum =0; double jsum=0; for (int k=0; k<correlationCoefficient[i].length; k++){ if(!Double.isInfinite(scores[i][k])&&!Double.isInfinite(scores[j][k])){ combinedSum += (scores[i][k]-means[i])*(scores[j][k]-means[j]); isum += Math.pow(scores[i][k]-means[i],2); jsum += Math.pow(scores[j][k]-means[j],2); } } correlationCoefficient[i][j]=combinedSum/(Math.pow(isum,0.5)*Math.pow(jsum,0.5)); } } return correlationCoefficient; } }
3,245
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ComparisonMethodOberacherWithIntensitiesAndMasses.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ComparisonMethodOberacherWithIntensitiesAndMasses.java
package de.unijena.bioinf.spectralcomparison; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; import de.unijena.bioinf.statistics.Result; public class ComparisonMethodOberacherWithIntensitiesAndMasses implements ComparisonMethod{ static public final String methodNameLong="OberacherWithIntensitiesAndMasses"; ParametersSpectralComparison p; public List<MassBank> s1; public List<MassBank> s2; public ComparisonMethodOberacherWithIntensitiesAndMasses(ParametersSpectralComparison p) { this.p=p; } public String getMethodNameLong(){ return methodNameLong; } public void setSpectra(List<MassBank> s1, List<MassBank> s2) { this.s1=s1; this.s2=s2; } public List<MassBank>[] getSpectra() { return new List[]{s1,s2}; } @Override public AlignmentMatrix getAlignmentMatrix() { Result[][] results=p.getPostProcess().getResultList(this); List<String> left=new ArrayList<String>(); for(MassBank m:s1)left.add(m.massbankID); List<String> right=new ArrayList<String>(); for(MassBank m:s2)right.add(m.massbankID); String queryFile=p.p1.getOutputFolderMassbank().getAbsolutePath(); String resultFile=p.p2.getOutputFolderMassbank().getAbsolutePath(); AlignmentMatrix matrix=new AlignmentMatrix(queryFile, resultFile, left, right, results); return matrix; } public Result getResult(List<double[]> peaksLeft, List<double[]> peaksRight){ int numberMatches=0; double intensityDiff=0; double massDiff=0; double intensitySum1=0; double intensitySum2=0; double maxLeft=0; for(double[] p:peaksLeft)maxLeft=Math.max(maxLeft, p[1]); double maxRight=0; for(double[] p:peaksRight)maxRight=Math.max(maxRight, p[1]); List<double[]> p1=new ArrayList<double[]>(); for(double[] p:peaksLeft)if(p[1]/maxLeft*100>=5)p1.add(new double[]{p[0], p[1]/maxLeft*100}); List<double[]> p2=new ArrayList<double[]>(); for(double[] p:peaksRight)if(p[1]/maxRight*100>=5)p2.add(new double[]{p[0], p[1]/maxRight*100}); for(double[] p:p1)intensitySum1+=p[1]; for(double[] p:p2)intensitySum2+=p[1]; for(double[] peaks1:p1){ double[] bestMatchingPeak=null; double error=Utils.getAbsoluteErrorForMass(peaks1[0], p.ppm, p.ae); for(double[] peaks2:p2){ double diff=Math.abs(peaks1[0]-peaks2[0]); if(diff<error&&(bestMatchingPeak==null||Math.abs(peaks1[0]-bestMatchingPeak[0])>diff)){ bestMatchingPeak=peaks2; } } if(bestMatchingPeak!=null){ numberMatches++; intensityDiff+=Math.abs(peaks1[1]-bestMatchingPeak[1]); massDiff+=Math.abs(peaks1[0]-bestMatchingPeak[0]); } } Result r=new Result(numberMatches, numberMatches!=0?1.0*Math.pow(numberMatches,4)*Math.pow(intensitySum1+2*intensitySum2,1.25)/(Math.pow(p1.size()+2*p2.size(),2)+intensityDiff+massDiff):0); return r; } public double[][] calculateFP(double [][] scores) { double[] means = new double[scores.length]; for (int i=0; i<scores.length; i++){ double sum =0; int n=0; for (int j=0; j<scores[i].length; j++){ if(!Double.isInfinite(scores[i][j])){ sum += scores[i][j]; n++; } } means[i] = sum/n; } double[][] correlationCoefficient = new double[scores.length][scores.length]; for (int i=0; i<correlationCoefficient.length; i++){ for (int j=0; j<correlationCoefficient.length; j++){ double combinedSum =0; double isum =0; double jsum=0; for (int k=0; k<correlationCoefficient[i].length; k++){ if(!Double.isInfinite(scores[i][k])&&!Double.isInfinite(scores[j][k])){ combinedSum += (scores[i][k]-means[i])*(scores[j][k]-means[j]); isum += Math.pow(scores[i][k]-means[i],2); jsum += Math.pow(scores[j][k]-means[j],2); } } correlationCoefficient[i][j]=combinedSum/(Math.pow(isum,0.5)*Math.pow(jsum,0.5)); } } return correlationCoefficient; } }
4,141
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ParametersSpectralComparison.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ParametersSpectralComparison.java
package de.unijena.bioinf.spectralcomparison; import java.io.File; import java.util.Arrays; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; public class ParametersSpectralComparison { public static enum COMPARISONMETHOD{OBERACHER, OBERACHERWITHINTENSITIES, OBERACHERWITHINTENSITIESANDMASSES, OBERACHERPEAKCOUNTING, MASSBANK, MASSBANKEFFECTIVEPEAKS, COSINEDISTANCE, TREEALIGNMENT, EQUALITY}; public static enum COMPARISONPOSTPROCESS{FP, SIMPLE}; static String sep=System.getProperty("file.separator"); String base; String baseRT="RunningTimes"; ParametersDecoySpectrumConstruction p1; ParametersDecoySpectrumConstruction p2; COMPARISONMETHOD m; COMPARISONPOSTPROCESS pp; String addFolder=""; String addFolderRunningTimes=""; public boolean rt=false; public boolean removePP=false; public double ppm; public double ae; public ParametersSpectralComparison(COMPARISONMETHOD m, COMPARISONPOSTPROCESS pp, double ppm, double ae, String addFolder, ParametersDecoySpectrumConstruction p1, ParametersDecoySpectrumConstruction p2){ this(m, pp, ppm, ae, p1, p2); this.addFolder=addFolder; } public ParametersSpectralComparison(COMPARISONMETHOD m, COMPARISONPOSTPROCESS pp, double ppm, double ae, ParametersDecoySpectrumConstruction p1, ParametersDecoySpectrumConstruction p2){ this.p1=p1; this.p2=p2; this.m=m; this.pp=pp; this.ppm=ppm; this.ae=ae; } public ParametersSpectralComparison(String[] argsAll){ int indexOfFirstDataset=Integer.MIN_VALUE; int indexOfSecondDataset=Integer.MIN_VALUE; for(int j=0;j<argsAll.length;j++){ if(argsAll[j].equals("-ds1"))indexOfFirstDataset=j; if(argsAll[j].equals("-ds2"))indexOfSecondDataset=j; } String args[]=Arrays.copyOfRange(argsAll, 0, indexOfFirstDataset); int i=0; while(i<args.length){ if(args[i].equals("-base"))this.base=args[++i]; if(args[i].equals("-method")){ String method=args[++i]; for(COMPARISONMETHOD m:COMPARISONMETHOD.values()){ if(method.equals(getComparisonMethodName(m)))this.m=m; } } if(args[i].equals("-addFolder"))this.addFolder=args[++i]; if(args[i].equals("-rt")){ this.rt=true; if(!args[i+1].startsWith("-"))addFolderRunningTimes=args[++i]; } if(args[i].equals("-rpp")){ this.removePP=true; } if(args[i].equals("-ppm"))this.ppm=Double.parseDouble(args[++i]); if(args[i].equals("-ae"))this.ae=Double.parseDouble(args[++i]); if(args[i].equals("-postprocess")){ String post=args[++i]; if(post.equals("FP"))this.pp=COMPARISONPOSTPROCESS.FP; if(post.equals("Simple"))this.pp=COMPARISONPOSTPROCESS.SIMPLE; } i++; } p1=new ParametersDecoySpectrumConstruction(Arrays.copyOfRange(argsAll, indexOfFirstDataset+1, indexOfSecondDataset)); p2=new ParametersDecoySpectrumConstruction(Arrays.copyOfRange(argsAll, indexOfSecondDataset+1, argsAll.length)); } public ComparisonMethod getComparisonMethod(){ switch(m){ case OBERACHER: return new ComparisonMethodOberacher(this); case OBERACHERWITHINTENSITIES: return new ComparisonMethodOberacherWithIntensities(this); case OBERACHERWITHINTENSITIESANDMASSES: return new ComparisonMethodOberacherWithIntensitiesAndMasses(this); case OBERACHERPEAKCOUNTING: return new ComparisonMethodOberacherPeakcounting(this); case MASSBANK: return new ComparisonMethodMassBank(this); case MASSBANKEFFECTIVEPEAKS: return new ComparisonMethodMassBankEffectivePeaks(this); case COSINEDISTANCE: return new ComparisonMethodCosineDistance(this); case TREEALIGNMENT: return new ComparisonMethodTreeAlignment(this); case EQUALITY: return new ComparisonMethodEquality(this); default: return null; } } public static String getComparisonMethodName(COMPARISONMETHOD m){ switch(m){ case OBERACHER: return ComparisonMethodOberacher.methodNameLong; case OBERACHERWITHINTENSITIES: return ComparisonMethodOberacherWithIntensities.methodNameLong; case OBERACHERWITHINTENSITIESANDMASSES: return ComparisonMethodOberacherWithIntensitiesAndMasses.methodNameLong; case OBERACHERPEAKCOUNTING: return ComparisonMethodOberacherPeakcounting.methodNameLong; case MASSBANK: return ComparisonMethodMassBank.methodNameLong; case MASSBANKEFFECTIVEPEAKS: return ComparisonMethodMassBankEffectivePeaks.methodNameLong; case COSINEDISTANCE: return ComparisonMethodCosineDistance.methodNameLong; case TREEALIGNMENT: return ComparisonMethodTreeAlignment.methodNameLong; case EQUALITY: return ComparisonMethodEquality.methodNameLong; default: return null; } } public String getSearchMethod(){//TODO: SearchMethodClass return getComparisonMethod().getMethodNameLong(); } public PostProcessMethod getPostProcess(){//TODO: SearchMethodClass switch(pp){ case FP: return new PostProcessMethodFingerprint(this); case SIMPLE: return new PostProcessMethodSimple(this); default: return null; } } public File getOutputFileComparison(){ return new File(base+sep+getSearchMethod()+sep+p1.getChargePath()+sep+p1.getMassbankFirstID()+"-"+p2.getMassbankFirstID()+(!addFolder.isEmpty()?(sep+p1.getMassbankFirstID()+p1.addFolder+"-"+p2.getMassbankFirstID()+addFolder):"")+getPostProcess().getMethodNameLong()+".csv"); } public boolean isCorrectCombination() { // TODO Auto-generated method stub return true; } public File getOutputFileRunningTime(){ return new File(base+sep+baseRT+sep+getSearchMethod()+sep+p1.getChargePath()+sep+p1.getMassbankFirstID()+"-"+p2.getMassbankFirstID()+(!addFolder.isEmpty()?(sep+p1.getMassbankFirstID()+p1.addFolder+"-"+p2.getMassbankFirstID()+addFolder):"")+getPostProcess().getMethodNameLong()+addFolderRunningTimes+".txt"); } }
5,823
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
PostProcessMethodFingerprint.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/PostProcessMethodFingerprint.java
package de.unijena.bioinf.spectralcomparison; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.statistics.Result; public class PostProcessMethodFingerprint implements PostProcessMethod{ static public final String methodNameLong="FP"; ParametersSpectralComparison p; public String getMethodNameLong(){ return methodNameLong; } public PostProcessMethodFingerprint(ParametersSpectralComparison p){ this.p=p; } @Override public Result[][] getResultList(ComparisonMethod cm) { List<MassBank>[] spectra=cm.getSpectra(); Result[][] results=new Result[spectra[0].size()][spectra[1].size()]; double[][] scoresQueryVsQuery=new double[spectra[0].size()][spectra[0].size()]; double[][] scoresDBVsQuery=new double[spectra[1].size()][spectra[0].size()]; for(int j=0;j<spectra[0].size();j++){ for(int i=0;i<spectra[0].size();i++){ Result r=cm.getResult(spectra[0].get(i).peaks, spectra[0].get(j).peaks); scoresQueryVsQuery[i][j]=r.score; } for(int i=0;i<spectra[1].size();i++){ Result r=cm.getResult(spectra[1].get(i).peaks, spectra[0].get(j).peaks); results[j][i]=r; scoresDBVsQuery[i][j]=r.score; } } double[][] scoresFP=calculateFP(scoresQueryVsQuery, scoresDBVsQuery); for(int i=0;i<scoresFP.length;i++){ for(int j=0; j<scoresFP[i].length;j++){ results[i][j].score=scoresFP[i][j]; } } return results; } public double[][] calculateFP(double [][] scoresQueryVsQuery, double[][] scoresDBVsQuery) { double[] meansQueryVsQuery = getMeans(scoresQueryVsQuery); double[] meansDBVsQuery = getMeans(scoresDBVsQuery); double[][] correlationCoefficient = new double[meansQueryVsQuery.length][meansDBVsQuery.length]; for (int i=0; i<meansQueryVsQuery.length; i++){ for (int j=0; j<meansDBVsQuery.length; j++){ double combinedSum =0; double isum =0; double jsum=0; for (int k=0; k<scoresQueryVsQuery[i].length; k++){ if(!Double.isInfinite(scoresQueryVsQuery[i][k])&&!Double.isInfinite(scoresDBVsQuery[j][k])){ combinedSum += (scoresQueryVsQuery[i][k]-meansQueryVsQuery[i])*(scoresDBVsQuery[j][k]-meansDBVsQuery[j]); isum += Math.pow(scoresQueryVsQuery[i][k]-meansQueryVsQuery[i],2); jsum += Math.pow(scoresDBVsQuery[j][k]-meansDBVsQuery[j],2); } } correlationCoefficient[i][j]=combinedSum/(Math.pow(isum,0.5)*Math.pow(jsum,0.5)); } } return correlationCoefficient; } public double[] getMeans(double[][] scores){ double[] means = new double[scores.length]; for (int i=0; i<scores.length; i++){ double sum =0; int n=0; for (int j=0; j<scores[i].length; j++){ if(!Double.isInfinite(scores[i][j])){ sum += scores[i][j]; n++; } } means[i] = sum/n; } return means; } }
2,943
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ComparisonMethod.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ComparisonMethod.java
package de.unijena.bioinf.spectralcomparison; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.statistics.Result; public interface ComparisonMethod { public String getMethodNameLong(); public void setSpectra(List<MassBank> s1, List<MassBank> s2); // public void setTrees(List<Tree> s1, List<Tree> s2); public List<MassBank>[] getSpectra(); public Result getResult(List<double[]> peaksLeft, List<double[]> peaksRight); public AlignmentMatrix getAlignmentMatrix(); }
536
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ComparisonMethodEquality.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/ComparisonMethodEquality.java
package de.unijena.bioinf.spectralcomparison; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; import de.unijena.bioinf.statistics.Result; public class ComparisonMethodEquality implements ComparisonMethod{ static public final String methodNameLong="Equality"; ParametersSpectralComparison p; public List<MassBank> s1; public List<MassBank> s2; public ComparisonMethodEquality(ParametersSpectralComparison p) { this.p=p; } public String getMethodNameLong(){ return methodNameLong; } public void setSpectra(List<MassBank> s1, List<MassBank> s2) { this.s1=s1; this.s2=s2; } public List<MassBank>[] getSpectra() { return new List[]{s1,s2}; } @Override public AlignmentMatrix getAlignmentMatrix() { Result[][] results=p.getPostProcess().getResultList(this); List<String> left=new ArrayList<String>(); for(MassBank m:s1)left.add(m.massbankID); List<String> right=new ArrayList<String>(); for(MassBank m:s2)right.add(m.massbankID); String queryFile=p.p1.getOutputFolderMassbank().getAbsolutePath(); String resultFile=p.p2.getOutputFolderMassbank().getAbsolutePath(); AlignmentMatrix matrix=new AlignmentMatrix(queryFile, resultFile, left, right, results); return matrix; } public Result getResult(List<double[]> peaksLeft, List<double[]> peaksRight){ Result resultNotEqual=new Result(0, 0); Result resultEqual=new Result(1, 1); List<double[]> p1=new ArrayList<double[]>(); for(double[] p:peaksLeft){ p1.add(new double[]{p[0],p[1]}); } List<double[]> p2=new ArrayList<double[]>(); for(double[] p:peaksRight){ p2.add(new double[]{p[0],p[1]}); } if(p1.size()!=p2.size())return resultNotEqual; for(double[] peaks1:p1){ boolean found=false; for(double[] peaks2:p2){ if(peaks1[0]==peaks2[0]&&peaks1[1]==peaks2[1]){ found=true; break; } } if(!found)return resultNotEqual; } return resultEqual; } // public double[][] calculateFP(double [][] scores) { // // double[] means = new double[scores.length]; // for (int i=0; i<scores.length; i++){ // double sum =0; // int n=0; // for (int j=0; j<scores[i].length; j++){ // if(!Double.isInfinite(scores[i][j])){ // sum += scores[i][j]; // n++; // } // } // means[i] = sum/n; // } // // double[][] correlationCoefficient = new double[scores.length][scores.length]; // for (int i=0; i<correlationCoefficient.length; i++){ // for (int j=0; j<correlationCoefficient.length; j++){ // // double combinedSum =0; // double isum =0; // double jsum=0; // // for (int k=0; k<correlationCoefficient[i].length; k++){ // if(!Double.isInfinite(scores[i][k])&&!Double.isInfinite(scores[j][k])){ // combinedSum += (scores[i][k]-means[i])*(scores[j][k]-means[j]); // isum += Math.pow(scores[i][k]-means[i],2); // jsum += Math.pow(scores[j][k]-means[j],2); // } // } // // correlationCoefficient[i][j]=combinedSum/(Math.pow(isum,0.5)*Math.pow(jsum,0.5)); // } // } // return correlationCoefficient; // } }
3,352
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
PostProcessMethod.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/PostProcessMethod.java
package de.unijena.bioinf.spectralcomparison; import de.unijena.bioinf.statistics.Result; public interface PostProcessMethod { public Result[][] getResultList(ComparisonMethod cm); public String getMethodNameLong(); }
233
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MSBlastSpectralComparison.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/spectralcomparison/MSBlastSpectralComparison.java
package de.unijena.bioinf.spectralcomparison; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.CHARGE; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.DATA; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.DATASET; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.METHOD; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.POSTPROCESS; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONMETHOD; import de.unijena.bioinf.spectralcomparison.ParametersSpectralComparison.COMPARISONPOSTPROCESS; //generating spectral alignments public class MSBlastSpectralComparison { public static void main (String args[]) throws Exception{ Locale.setDefault(Locale.US); ParametersSpectralComparison p=new ParametersSpectralComparison(args); if(!p.isCorrectCombination()){ System.err.println("\""+Arrays.toString(args)+"\" is not a correct parameter combination."); return; } System.out.println(p.getOutputFileComparison()); List<MassBank> left=new ArrayList<MassBank>(); List<MassBank> right=new ArrayList<MassBank>(); List<MassBank> both=new ArrayList<MassBank>(); for(File f:p.p1.getOutputFolderMassbank().listFiles()){ MassBank m=new MassBank(f); if(p.removePP)m.removeParentPeaks(p.ppm, p.ae); left.add(m); both.add(m); } System.out.println(p.p2.getOutputFolderMassbank().getAbsolutePath()); for(File f:p.p2.getOutputFolderMassbank().listFiles()){ MassBank m=new MassBank(f); if(p.removePP)m.removeParentPeaks(p.ppm, p.ae); right.add(m); both.add(m); } ComparisonMethod comparison=p.getComparisonMethod(); comparison.setSpectra(left, right); AlignmentMatrix matrix=comparison.getAlignmentMatrix(); matrix.writeToCSV(p.getOutputFileComparison()); System.out.println("... finished"); } }
2,190
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
Utils.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/deocy/Utils.java
package de.unijena.bioinf.deocy; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TreeMap; import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula; import de.unijena.bioinf.babelms.dot.Edge; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.babelms.dot.Parser; import de.unijena.bioinf.babelms.dot.Vertex; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.decoy.model.DecoyTreeEdge; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; public class Utils { public static Map<File,Graph> readGraphs(File input){ return readGraphs(input,true); } public static Map<File,Graph> readGraphs(File input,boolean storeGraphs){ Map<File,Graph> result=new HashMap<File,Graph>(); for(File f:input.listFiles()){ if(f.getName().endsWith(".dot")){ try{ Graph g=Parser.parse(new FileReader(f)); if(g!=null&&g.getVertices().size()>1){ result.put(f,g); System.out.println("Graph for "+f.getName()+" is read."); }else{ System.err.println("Graph for "+f.getName()+" is empty."); } }catch(IOException e){ System.err.println("Graph "+f+" was not read!"); } }else if(f.getName().endsWith(".ms")||f.getName().endsWith(".txt")){ try{ BufferedReader br=new BufferedReader(new FileReader(f)); Graph g=new Graph(); List<Peak> peaks=new ArrayList<Peak>(); String line=""; MolecularFormula mf=null; double ionization=0; boolean intrinsicCharged=false; Double parentMass=null; double maxIntensity=0; while((line=br.readLine())!=null){ if(line.startsWith(">formula")){ mf=MolecularFormula.parse(line.substring(9)); if(mf.maybeCharged()){ ionization=-0.0019666; intrinsicCharged=true; } } if(line.startsWith(">parentmass")){ parentMass=Double.parseDouble(line.substring(12)); } if(line.startsWith(">ionization")&&!intrinsicCharged){ String ion=line.substring(12); if(ion.equals("[M+H]+"))ionization=1.00728; else if(ion.equals("[M+H-H2O]+"))ionization=-17.00219; else if(ion.equals("[M+Na]+"))ionization=22.98922; else if(ion.equals("[M+NH4]+"))ionization=18.03437; else if(ion.equals("[M+K]+"))ionization=39.098301; else{ System.err.println("Ionization unknown"); continue; } } if(line.startsWith(">charge")&&!intrinsicCharged){ String charge=line.substring(8); if(charge.equals("1"))ionization=1.00728; } if(line.matches("\\d*[\\.\\d*]+\\s\\d*[\\.\\d*]+")){ String l[]=line.split("\\s"); double mz=Double.parseDouble(l[0]); double intensity=Double.parseDouble(l[1]); if(mz-0.1<mf.getMass()+ionization)peaks.add(new Peak(mz, intensity)); maxIntensity=Math.max(maxIntensity,intensity); } } if(peaks.isEmpty())continue; Collections.sort(peaks); List<List<Peak>> peakGroups=new ArrayList<List<Peak>>(); List<Peak> currentListPeaks=new ArrayList<Peak>(); peakGroups.add(currentListPeaks); for(int i=0;i<peaks.size();i++){ if(i==0){ currentListPeaks.add(peaks.get(i)); }else{ double error=Utils.getAbsoluteErrorForMass(peaks.get(i).mz, 10, 2); if(Math.abs(peaks.get(i).mz-peaks.get(i-1).mz)>error){ currentListPeaks=new ArrayList<Peak>(); peakGroups.add(currentListPeaks); } currentListPeaks.add(peaks.get(i)); } } int i=0; boolean parentPeakFound=false; for(List<Peak> peakGroup:peakGroups){ Peak peakWithMaxInt=null; for(Peak p:peakGroup){ if(peakWithMaxInt==null||peakWithMaxInt.intensity<p.intensity){ peakWithMaxInt=p; } } Vertex currentVertex = new Vertex("v"+i++); if(Math.abs(peakWithMaxInt.mz-ionization-mf.getMass())<0.2){ currentVertex.getProperties().put("label", mf.toString()+"\\nexact mass "+(peakWithMaxInt.mz-ionization)+" Da, "+peakWithMaxInt.intensity+"%"); parentPeakFound=true; }else{ currentVertex.getProperties().put("label", "exact mass "+(peakWithMaxInt.mz-ionization)+" Da, "+peakWithMaxInt.intensity+"%"); } g.getVertices().add(currentVertex); } if(!parentPeakFound){ if(parentMass==null){ parentMass=mf.getMass()+ionization; } System.out.println("parent peak added"); Vertex currentVertex = new Vertex("v"+i++); currentVertex.getProperties().put("label", mf.toString()+"\\nexact mass "+(parentMass-ionization)+" Da, 1%"); g.getVertices().add(currentVertex); } // if(!parentPeakFound){ // System.err.println("no parent peak found for "+f.getName()); // continue; // } if(g.getVertices().size()<=1){ System.err.println("no peaks found for "+f.getName()); continue; } if(storeGraphs)result.put(f,g); else result.put(f,null); br.close(); System.out.println("Graph for "+f.getName()+" is read."); }catch(IOException e){ System.err.println("Could not read file "+f.getAbsolutePath()); } } } return result; } public static double getIntensityFromVertex(Vertex v){ String label=v.getProperties().get("label"); int start=label.indexOf("Da,")+4; int end=label.indexOf("%"); return Double.parseDouble(label.substring(start,end).trim()); } public static void getVerticesOfSpecialDepth(DefaultDecoyTree g, DecoyTreeVertex root, int depth, Set<DecoyTreeVertex> vertices){ if(depth==0){ vertices.add(root); }else{ for(Edge e:g.getOutgoingEdgesFor(root)){ getVerticesOfSpecialDepth(g, g.getVertex(e.getTail()), depth-1, vertices); } } } public static double getAbsoluteErrorForMass(double mass, double ppm, double ae){ return Math.max(ppm*1e-6*mass, ae*1e-3); } } class Peak implements Comparable<Peak>{ double mz; double intensity; public Peak(double mz, double intensity){ this.mz=mz; this.intensity=intensity; } @Override public int compareTo(Peak o) { return Double.compare(mz, o.mz); } }
6,632
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
DecoySpectrum.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/decoytrees/DecoySpectrum.java
package de.unijena.bioinf.decoy.decoytrees; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeMap; import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.babelms.dot.Vertex; import de.unijena.bioinf.decoy.model.DecoyTreeEdge; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.decoy.model.VertexComparator; public interface DecoySpectrum { public void writeAsDot(File file) throws IOException; public boolean isTree(); public void writeAsMS(File file) throws IOException; public MolecularFormula getParent(); public List<double[]> getPeaks(); public void writeAsMassbank(File outputFolderMassbank, List<double[]> peaks, MolecularFormula parent, double massParentIon, String acc, String string, String instrumentName, String inchi, Boolean positive, boolean contains) throws IOException ; public boolean equalsGraph(Graph g); }
1,430
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
DefaultDecoyTree.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/decoytrees/DefaultDecoyTree.java
package de.unijena.bioinf.decoy.decoytrees; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeMap; import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula; import de.unijena.bioinf.babelms.dot.Edge; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.babelms.dot.Vertex; import de.unijena.bioinf.decoy.model.DecoyTreeEdge; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.decoy.model.VertexComparator; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.POSTPROCESS; public class DefaultDecoyTree extends DefaultDecoySpectrum implements Cloneable,DecoySpectrum{ private final ArrayList<DecoyTreeVertex> vertices; private final ArrayList<DecoyTreeEdge> edges; public boolean isPositive=true; public DefaultDecoyTree() { this.vertices = new ArrayList<DecoyTreeVertex>(); this.edges = new ArrayList<DecoyTreeEdge>(); } public DefaultDecoyTree(Graph g) { this.vertices = new ArrayList<DecoyTreeVertex>(g.getVertices().size()); this.edges = new ArrayList<DecoyTreeEdge>(g.getEdges().size()); for (Vertex v : g.getVertices()) vertices.add(new DecoyTreeVertex(v)); for (Edge e : g.getEdges()) edges.add(new DecoyTreeEdge(e)); } public DefaultDecoyTree(DefaultDecoyTree g) { this.vertices = new ArrayList<DecoyTreeVertex>(g.getVertices().size()); this.edges = new ArrayList<DecoyTreeEdge>(g.getEdges().size()); for (Vertex v : g.getVertices()) vertices.add(new DecoyTreeVertex(v)); for (Edge e : g.getEdges()) edges.add(new DecoyTreeEdge(e)); } public void writeAsDot(Writer writer) throws IOException { final BufferedWriter bw = new BufferedWriter(writer); bw.write("strict digraph {\n"); for (DecoyTreeVertex v : vertices) { bw.write(v.toString()); bw.write('\n'); } for (DecoyTreeEdge e : edges) { bw.write(e.toString()); bw.write('\n'); } bw.write("}"); bw.flush(); } public void writeAsDot(File f) throws IOException { if(!f.getParentFile().exists())f.getParentFile().mkdirs(); final BufferedWriter bw = new BufferedWriter(new FileWriter(f)); writeAsDot(bw); } public List<DecoyTreeEdge> getIncommingEdgesFor(DecoyTreeVertex vertex) { return getIncommingEdgesFor(vertex.getName()); } public MolecularFormula getParent(){ return getRoot().mf; } public boolean isTree(){ for (DecoyTreeVertex v : vertices) { if(v.mf==null) return false; } return true; } public DecoyTreeVertex getRoot() { final HashSet<String> vertices = new HashSet<String>(); for (DecoyTreeEdge e : edges) { vertices.add(e.getHead()); } for (DecoyTreeEdge e : edges) { vertices.remove(e.getTail()); } if (vertices.isEmpty()){ DecoyTreeVertex result=null; for (DecoyTreeVertex v : this.vertices) { if(v.mf!=null&&(result==null||Math.abs(result.mf.getMass()-result.mz)>Math.abs(v.mf.getMass()-v.mz)))result=v; } return result; } final String s = vertices.iterator().next(); return getVertex(s); } public DecoyTreeVertex getVertex(String name) { for (DecoyTreeVertex u : vertices) if (u.getName().equals(name)) return u; return null; } public List<DecoyTreeEdge> getIncommingEdgesFor(String vertex) { final ArrayList<DecoyTreeEdge> neighbours = new ArrayList<DecoyTreeEdge>(); for (DecoyTreeEdge e : edges) { if (e.getTail().equals(vertex)) neighbours.add(e); } return neighbours; } public List<DecoyTreeEdge> getOutgoingEdgesFor(Vertex vertex) { return getOutgoingEdgesFor(vertex.getName()); } public List<DecoyTreeEdge> getOutgoingEdgesFor(String vertex) { final ArrayList<DecoyTreeEdge> neighbours = new ArrayList<DecoyTreeEdge>(); for (DecoyTreeEdge e : edges) { if (e.getHead().equals(vertex)) neighbours.add(e); } return neighbours; } public DecoyTreeEdge getEdgeFor(DecoyTreeVertex u, DecoyTreeVertex v) { return getEdgeFor(u.getName(), v.getName()); } public DecoyTreeEdge getEdgeFor(String u, String v) { for (DecoyTreeEdge e : edges) { if (e.getHead().equals(u) && e.getTail().equals(v)) return e; } return null; } public ArrayList<DecoyTreeVertex> getVertices() { return vertices; } public ArrayList<DecoyTreeEdge> getEdges() { return edges; } public List<double[]> getPeaks(){ return getPeaks(Double.POSITIVE_INFINITY); } public List<double[]> getOriginalPeaks(){ return getOriginalPeaks(Double.POSITIVE_INFINITY); } public List<double[]> getPeaks(double maxMass){ List<double[]> peaks=new ArrayList<double[]>(); for (DecoyTreeVertex v : getVertices()) { if(v.mz<maxMass)peaks.add(new double[]{v.mf.getMass(),v.intensity}); } return peaks; } public List<double[]> getOriginalPeaks(double maxMass){ List<double[]> peaks=new ArrayList<double[]>(); for (DecoyTreeVertex v : getVertices()) { if(v.mz<maxMass)peaks.add(new double[]{v.mz,v.intensity}); } return peaks; } public List<double[]> getPeaksIncludingMax(double maxMass){ List<double[]> peaks=new ArrayList<double[]>(); for (DecoyTreeVertex v : getVertices()) { if(v.mz<=maxMass)peaks.add(new double[]{v.mz,v.intensity}); } return peaks; } public static List<double[]> getPeaksIncludingMax(Graph g, double maxMass){ List<double[]> peaks=new ArrayList<double[]>(); for (Vertex v : g.getVertices()) { MolecularFormula mf=DecoyTreeVertex.getMolecularFormulaFromLabel(v); Double mz=DecoyTreeVertex.getExactMassFromLabel(v); mz=(mz==null)?mf.getMass():mz; double intensity=Utils.getIntensityFromVertex(v); if(mz<=maxMass)peaks.add(new double[]{mz,intensity}); } return peaks; } @Override public boolean equalsGraph(Graph g) { for(Vertex v:g.getVertices()){ boolean found=false; DecoyTreeVertex dtv=new DecoyTreeVertex(v); Double mz=dtv.mz; Double intensity=dtv.intensity; for(DecoyTreeVertex dtv2:this.vertices){ if(mz.equals(dtv2.getExactMassFromLabel())&&intensity.equals(dtv2.intensity)){ found=true; break; } } if(!found)return false; } for(DecoyTreeVertex dtv2:this.vertices){ boolean found=false; for(Vertex v:g.getVertices()){ DecoyTreeVertex dtv=new DecoyTreeVertex(v); Double mz=dtv.mz; Double intensity=dtv.intensity; if(mz.equals(dtv2.getExactMassFromLabel())&&intensity.equals(dtv2.intensity)){ found=true; break; } } if(!found)return false; } return true; } }
7,180
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
DefaultDecoySpectrum.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/decoytrees/DefaultDecoySpectrum.java
package de.unijena.bioinf.decoy.decoytrees; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.babelms.dot.Vertex; import de.unijena.bioinf.decoy.model.DecoyTreeEdge; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.decoy.model.MassBank; import de.unijena.bioinf.decoy.model.VertexComparator; import de.unijena.bioinf.deocy.Utils; public class DefaultDecoySpectrum implements DecoySpectrum { MolecularFormula parent; List<double[]> peaks; public DefaultDecoySpectrum(){} public DefaultDecoySpectrum(MolecularFormula parent, List<double[]> peaks){ this.parent=parent; this.peaks=peaks; } @Override public MolecularFormula getParent() { return parent; } @Override public List<double[]> getPeaks() { return peaks; } public String writeToString() { final StringWriter strw = new StringWriter(); try { writeAsDot(strw); } catch (IOException e) { e.printStackTrace(); } return strw.toString(); } public void writeAsDot(Writer writer) throws IOException { } public void writeAsDot(File file) throws IOException { } public void writeAsMassbank(File outputFolderMassbank, List<double[]> peaks, MolecularFormula parent, double massParentIon, String acc, String recordTitle, String instrumentName, String inchi, Boolean positive, boolean containsPPDiff) throws IOException { MassBank mbReal=new MassBank(peaks, parent, massParentIon, acc, recordTitle, instrumentName, inchi, positive, containsPPDiff); mbReal.writeSpectrumAsMassbank(outputFolderMassbank); } public void writeAsMS(File file) throws IOException { double hAdduct=1.00728; final BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(">compound "+file.getName().substring(0,file.getName().lastIndexOf("."))+"\n"); bw.write(">formula "+getParent()+"\n"); bw.write(">parentmass "+(getParent().getMass()+hAdduct)+"\n"); bw.write(">ionization [M+H]+\n\n"); List<double[]> peaks=getPeaks(); double tic=0; for (double[] p : peaks) { tic+=p[1]; } bw.write(">collision 0\n"); bw.write(">tic "+tic+"\n"); for (double[] p : peaks) { bw.write((p[0]+hAdduct)+" "+p[1]+"\n"); } bw.flush(); bw.close(); } public boolean isTree(){ return false; } @Override public boolean equalsGraph(Graph g) { for(Vertex v:g.getVertices()){ boolean found=false; DecoyTreeVertex dtv=new DecoyTreeVertex(v); Double mz=dtv.mz; Double intensity=dtv.intensity; for(double[] d:this.peaks){ if(mz.equals(d[0])&&intensity.equals(d[1])){ found=true; break; } } if(!found)return false; } for(double[] d:this.peaks){ boolean found=false; for(Vertex v:g.getVertices()){ DecoyTreeVertex dtv=new DecoyTreeVertex(v); Double mz=dtv.mz; Double intensity=dtv.intensity; if(mz.equals(d[0])&&intensity.equals(d[1])){ found=true; break; } } if(!found)return false; } return true; } }
3,398
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
VertexComparator.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/VertexComparator.java
package de.unijena.bioinf.decoy.model; import java.util.Comparator; public class VertexComparator implements Comparator<DecoyTreeVertex>{ @Override public int compare(DecoyTreeVertex o1, DecoyTreeVertex o2) { return Double.compare(o1.mf.getMass(),o2.mf.getMass()); } }
288
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
DecoyTreeVertex.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/DecoyTreeVertex.java
package de.unijena.bioinf.decoy.model; import java.util.Iterator; import java.util.Map; import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula; import de.unijena.bioinf.babelms.dot.Vertex; import de.unijena.bioinf.deocy.Utils; public class DecoyTreeVertex extends Vertex{ public MolecularFormula mf; public double mz; public double intensity; // public DecoyTreeVertex(String name) { // super(name); // } public DecoyTreeVertex(Vertex v) { super(v); mf=this.getMolecularFormulaFromLabel(); Double mz=this.getExactMassFromLabel(); this.mz=(mz==null)?mf.getMass():mz; intensity=Utils.getIntensityFromVertex(v); } public String toString() { final StringBuilder b = new StringBuilder(); b.append(name); b.append(" ["); b.append("label=\""+mf.formatByKerstin()+"\\n"+mf.getMass()+" Da, "+intensity+" %\""); b.append("];"); return b.toString(); } public MolecularFormula getMolecularFormulaFromLabel(){ if(!getProperties().get("label").contains("\\n"))return null; return MolecularFormula.parse(getProperties().get("label").replaceAll("\\\\n.*","")); } public static MolecularFormula getMolecularFormulaFromLabel(Vertex v){ if(!v.getProperties().get("label").contains("\\n"))return null; return MolecularFormula.parse(v.getProperties().get("label").replaceAll("\\\\n.*","")); } public Double getExactMassFromLabel(){ String l=getProperties().get("label"); if(!l.contains("exact mass")) return null; int start=l.indexOf("exact mass")+11; int end=l.indexOf("Da"); return Double.parseDouble(l.substring(start,end).trim()); } public static Double getExactMassFromLabel(Vertex v){ String l=v.getProperties().get("label"); if(!l.contains("exact mass")) return null; int start=l.indexOf("exact mass")+11; int end=l.indexOf("Da"); return Double.parseDouble(l.substring(start,end).trim()); } }
1,933
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MassBank.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/MassBank.java
package de.unijena.bioinf.decoy.model; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula; import de.unijena.bioinf.deocy.Utils; public class MassBank implements java.io.Serializable, Comparable<MassBank>{ /** * */ private static final long serialVersionUID = -4955544804945648760L; /** * */ static String sep=System.getProperty("file.separator"); public String massbankID; public String recordTitle; public String instrument; public MolecularFormula mf=null; public Double massParentIon=null; public String inchi=null; public String inchiBackup=null; public boolean isPositive; public List<double[]> peaks; Double idealParentIon=null; public MassBank(File f) throws Exception{ this(f, true); } public MassBank(File f, boolean withPeaks) throws Exception{ BufferedReader br=new BufferedReader(new FileReader(f)); String line; while((line=br.readLine())!=null){ if(line.startsWith("ACCESSION"))this.massbankID=line.substring(11); if(line.startsWith("RECORD_TITLE"))this.recordTitle=line.substring(14); if(line.startsWith("CH$FORMULA"))if(this.mf==null)this.mf=MolecularFormula.parse(line.substring(12)); if(line.startsWith("AC$INSTRUMENT"))this.instrument=line.substring(15); if(line.startsWith("MS$FOCUSED_ION: PRECURSOR_TYPE")){ if(line.substring(31).equals("[M+H]+"))isPositive=true; else isPositive=false; if(this.mf!=null){ double hAdduct=isPositive?1.00728:-1.00728; idealParentIon=this.mf.getMass()+hAdduct; } } if(line.startsWith("CH$IUPAC")){ String l=line.substring(10); this.inchiBackup=l; if(!l.equals("N/A")){ String tmp[]=l.split("/"); String first=tmp[1]; int i=first.indexOf('.'); if(i>=0)first=first.substring(0,i); // this.mf=MolecularFormula.parse(first); String second=tmp[2]; i=second.indexOf(';'); if(i>=0)second=second.substring(0,i); this.inchi=first+"/"+second; } } if(line.startsWith("PK$PEAK")){ peaks=new ArrayList<double[]>(); while(!(line=br.readLine()).equals("//")){ String[] p=line.trim().split(" "); double mz=Double.parseDouble(p[0]); if(massParentIon==null||Math.abs(massParentIon-idealParentIon)>Math.abs(mz-idealParentIon))massParentIon=mz; if(withPeaks)peaks.add(new double[]{mz,Double.parseDouble(p[1]),Double.parseDouble(p[2])}); } } } br.close(); } public void removeParentPeaks(double ppm, double ae){ Iterator<double[]> peakIt=peaks.iterator(); while(peakIt.hasNext()){ double[] p=peakIt.next(); double error=Utils.getAbsoluteErrorForMass(p[0], ppm, ae); if(Math.abs(p[0]-idealParentIon)<error)peakIt.remove(); } } public MassBank(List<double[]> p, MolecularFormula mf, double massParentIon, String massbankID, String recordTitle, String instrument, String inchi, boolean isPositive, boolean useParentPeakDiffs) throws IOException { this.massbankID=massbankID; this.recordTitle=recordTitle; this.mf=mf; this.massParentIon=massParentIon; this.instrument=instrument; this.inchi=inchi; this.isPositive=isPositive; peaks=new ArrayList<double[]>(p); if(useParentPeakDiffs){ List<double[]> newPeaks=new ArrayList<double[]>(); double maxIntensity=0; for(int i=0;i<p.size();i++){ maxIntensity=Math.max(p.get(i)[1], maxIntensity); } for (double[] v : p) { double diffMass=mf.getMass()-v[0]; if(diffMass>0){ newPeaks.add(new double[]{mf.getMass()-v[0], maxIntensity-v[1]}); } } peaks.addAll(newPeaks); } } public void writeSpectrumAsMassbank(File folder) throws IOException { if(!folder.exists())folder.mkdirs(); BufferedWriter writer=new BufferedWriter(new FileWriter(folder+sep+massbankID+".txt")); double hAdduct=isPositive?1.00728:-1.00728; final BufferedWriter bw = new BufferedWriter(writer); bw.write("ACCESSION: "+massbankID+"\n"); bw.write("RECORD_TITLE: "+recordTitle+"\n"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd"); bw.write("DATE: "+sdf.format(Calendar.getInstance().getTime())+"\n"); bw.write("AUTHORS: Administrator\n"); bw.write("LICENSE: CC BY-SA\n"); bw.write("CH$NAME: "+recordTitle+"\n"); bw.write("CH$COMPOUND_CLASS: Natural Product\n"); bw.write("CH$FORMULA: "+this.mf+"\n"); bw.write("CH$EXACT_MASS: "+this.mf.getMass()+"\n"); bw.write("CH$SMILES: N/A\n"); bw.write("CH$IUPAC: "+(inchi==null?"N/A":inchi)+"\n"); bw.write("CH$LINK: N/A\n"); bw.write("AC$INSTRUMENT: "+instrument+"\n"); bw.write("AC$INSTRUMENT_TYPE: "+instrument+"\n"); bw.write("AC$MASS_SPECTROMETRY: MS_TYPE MS2\n"); bw.write("AC$MASS_SPECTROMETRY: ION_MODE POSITIVE\n"); bw.write("AC$MASS_SPECTROMETRY: COLLISION_ENERGY 10 V\n"); bw.write("MS$FOCUSED_ION: PRECURSOR_M/Z "+Math.round(this.mf.getMass()+hAdduct)+"\n"); bw.write("MS$FOCUSED_ION: PRECURSOR_TYPE [M+H]+\n"); bw.write("PK$NUM_PEAK: "+peaks.size()+"\n"); bw.write("PK$PEAK: m/z int. rel.int.\n"); double maxIntensity=0; for(int i=0;i<peaks.size();i++){ maxIntensity=Math.max(peaks.get(i)[1], maxIntensity); } Map<Double,Double> intensityMap=new TreeMap<Double,Double>(); for(int i=0;i<peaks.size();i++){ double mass=Math.round(peaks.get(i)[0]*1000000)/1000000.0; double intensity=peaks.get(i)[1]; if(!intensityMap.containsKey(mass)){ intensityMap.put(mass,intensity); }else{ if(intensityMap.get(mass)<intensity){ intensityMap.put(mass,intensity); } } } List<double[]> p =new ArrayList<double[]>(); for (Entry<Double,Double> e : intensityMap.entrySet()) { p.add(new double[]{e.getKey()+hAdduct, e.getValue(), e.getValue()/maxIntensity*999}); } for (double[] v : p) { bw.write(" "+v[0]+" "+v[1]+" "+Math.round(v[2])+"\n"); } bw.write("//\n"); bw.flush(); bw.close(); } public boolean isDecoy(){ return (!instrument.contains("Original")); } public boolean hasEqualInChiKey(MassBank mb){ if(this.inchi==null||mb.inchi==null)return false; return (this.mf.equals(mb.mf)&&this.inchi.equals(mb.inchi)); } public boolean hasEqualMass(MassBank mb, double ppm, double ae){ double error=Utils.getAbsoluteErrorForMass(getMassParentIon(), ppm, ae); // if(Math.abs(getMassParentIon()-mb.getMassParentIon())>error){ // if(Math.abs(getMassParentIon()-mb.idealParentIon)>error){ if(Math.abs(idealParentIon-mb.idealParentIon)>error){ return false; } return true; } public double getMassParentIon(){ return massParentIon; } @Override public int compareTo(MassBank o) { return this.massbankID.compareTo(o.massbankID); } }
7,211
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
DecoyTreeEdge.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/DecoyTreeEdge.java
package de.unijena.bioinf.decoy.model; import java.util.Iterator; import java.util.Map; import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula; import de.unijena.bioinf.babelms.dot.Edge; import de.unijena.bioinf.deocy.Utils; public class DecoyTreeEdge extends Edge{ public MolecularFormula mf; public DecoyTreeEdge(Edge e) { super(e); mf=this.getMolecularFormulaFromLabel(); } public void redirect(){ String tail=getTail(); setTail(getHead()); setHead(tail); } public void setHead(String u) { this.u=u; } public void setTail(String v) { this.v=v; } public String toString() { final StringBuilder b = new StringBuilder(); b.append(u).append(" -> ").append(v); b.append(" ["); b.append("label=\""+mf.formatByKerstin()+"\""); b.append("];"); return b.toString(); } public MolecularFormula getMolecularFormulaFromLabel(){ return MolecularFormula.parse(getProperties().get("label").replaceAll("\\\\n.*","")); } }
1,074
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ConditionalPeaksConstructor.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/decoytreeconstructors/ConditionalPeaksConstructor.java
package de.unijena.bioinf.decoy.model.decoytreeconstructors; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.decoy.decoytrees.DecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; public class ConditionalPeaksConstructor extends DefaultDecoyTreeConstructor implements DecoySpectrumConstructor{ static private TreeMap<Double, List<Graph>> m=null; static public final String methodNameLong="ConditionalPeaks"; Random r = new Random(); public ConditionalPeaksConstructor(ParametersDecoySpectrumConstruction p) { super(p); } public String getMethodNameLong(){ return methodNameLong; } public DecoySpectrum getDecoySpectrum(){ List<double[]> allPeaksDecoy=new ArrayList<double[]>(); DecoyTreeVertex root=inputGraph.getRoot(); allPeaksDecoy.add(new double[]{root.mz,root.intensity}); Map<Double,List<double[]>> allPeaksDB=getAllConditionalPeaksFromDB(inputGraph.getRoot().mz); for(int i=0;i<inputGraph.getVertices().size()-1;i++){ List<double[]> currentPeaks=new ArrayList<double[]>(); // for(double[] p:allPeaksDecoy){ double[] p=allPeaksDecoy.get(allPeaksDecoy.size()-1); double error=Utils.getAbsoluteErrorForMass(p[0], this.p.ppm, this.p.ae); for(Entry<Double, List<double[]>> peaksDB:allPeaksDB.entrySet()){ if(Math.abs(p[0]-peaksDB.getKey())<error)currentPeaks.addAll(peaksDB.getValue()); } int index=r.nextInt(currentPeaks.size()); allPeaksDecoy.add(currentPeaks.get(index)); double addedMass=currentPeaks.get(index)[0]; error=Utils.getAbsoluteErrorForMass(addedMass, this.p.ppm, this.p.ae); for(List<double[]> peaks:allPeaksDB.values()){ Iterator<double[]> it=peaks.iterator(); while(it.hasNext()){ if(Math.abs(it.next()[0]-addedMass)<error)it.remove(); } } } DefaultDecoySpectrum s=new DefaultDecoySpectrum(inputGraph.getParent(), allPeaksDecoy); return s; } Map<Double,List<double[]>> getAllConditionalPeaksFromDB(double maxMass){ return getAllConditionalPeaksFromDB(maxMass, p.getAllGraphsInOriginal().values()); } public static Map<Double,List<double[]>> getAllConditionalPeaksFromDB(double maxMass, Collection<Graph> graphsInOriginalDB){ Map<Double, List<double[]>> result=new HashMap<Double, List<double[]>>(); for(Graph g:graphsInOriginalDB){ DefaultDecoyTree dt=new DefaultDecoyTree(g); List<double[]> peaks=dt.getPeaksIncludingMax(maxMass); for(int i=0;i<peaks.size();i++){ for(int j=0;j<peaks.size();j++){ if(i!=j){ if(!result.containsKey(peaks.get(i)[0]))result.put(peaks.get(i)[0],new ArrayList<double[]>()); result.get(peaks.get(i)[0]).add(peaks.get(j)); } } } } return result; } public static List<double[]> getAllPeaksFromDB(double maxMass, Collection<Graph> graphsInOriginalDB){ List<double[]> result=new ArrayList<double[]>(); for(Graph g:graphsInOriginalDB){ DefaultDecoyTree dt=new DefaultDecoyTree(g); List<double[]> peaks=dt.getPeaksIncludingMax(maxMass); result.addAll(peaks); } return result; } }
3,699
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
MixedSpectrumConstructor.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/decoytreeconstructors/MixedSpectrumConstructor.java
package de.unijena.bioinf.decoy.model.decoytreeconstructors; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.babelms.dot.Vertex; import de.unijena.bioinf.decoy.decoytrees.DecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; public class MixedSpectrumConstructor extends DefaultDecoyTreeConstructor implements DecoySpectrumConstructor{ static public final String methodNameLong="MixedSpectrum"; Random r = new Random(); public MixedSpectrumConstructor(ParametersDecoySpectrumConstruction p) { super(p); } public String getMethodNameLong(){ return methodNameLong; } // public DecoySpectrum getDecoySpectrum(){ // List<double[]> allPeaksDecoy=new ArrayList<double[]>(); // DecoyTreeVertex root=inputGraph.getRoot(); // allPeaksDecoy.add(new double[]{root.mz,root.intensity}); // // // List<Graph> allGraphs=new ArrayList<Graph>(); // allGraphs.addAll(p.getAllGraphsInOriginal().values()); // allGraphs.remove(inputGraph); // int numberGraphs=0; // List<double[]> allPeaksDecoyTmp=new ArrayList<double[]>(); // while(numberGraphs<2||allPeaksDecoyTmp.size()<3*inputGraph.getVertices().size()){ // int i=r.nextInt(allGraphs.size()); // Graph currGraph=allGraphs.get(i); // DefaultDecoyTree dt=new DefaultDecoyTree(currGraph); // allGraphs.remove(i); // boolean GraphUsed=false; // for(DecoyTreeVertex v:dt.getVertices()){ // double mass=v.mz; // if(mass<root.mz){ // allPeaksDecoyTmp.add(new double[]{mass, v.intensity}); // GraphUsed=true; // } // } // if(GraphUsed)numberGraphs++; // } // // for (int j=0;j<inputGraph.getVertices().size()-1;j++){ // int i=r.nextInt(allPeaksDecoyTmp.size()); // allPeaksDecoy.add(allPeaksDecoyTmp.get(i)); // allPeaksDecoyTmp.remove(i); // } // // DefaultDecoySpectrum s=new DefaultDecoySpectrum(inputGraph.getParent(), allPeaksDecoy); // return s; // } public DecoySpectrum getDecoySpectrum(){ List<double[]> allPeaksDecoy=new ArrayList<double[]>(); DecoyTreeVertex root=inputGraph.getRoot(); allPeaksDecoy.add(new double[]{root.mz,root.intensity}); List<List<double[]>> allPeaks=new ArrayList<List<double[]>>(); allPeaks.addAll(p.getAllPeaksInOriginal().values()); int numberGraphs=0; List<double[]> allPeaksDecoyTmp=new ArrayList<double[]>(); while(numberGraphs<2||allPeaksDecoyTmp.size()<3*inputGraph.getVertices().size()){ int i=r.nextInt(allPeaks.size()); List<double[]> currPeaks=allPeaks.get(i); allPeaks.remove(i); boolean GraphUsed=false; for(double[] d:currPeaks){ double mass=d[0]; if(mass<root.mz){ allPeaksDecoyTmp.add(new double[]{mass, d[1]}); GraphUsed=true; } } if(GraphUsed)numberGraphs++; } for (int j=0;j<inputGraph.getVertices().size()-1;j++){ int i=r.nextInt(allPeaksDecoyTmp.size()); allPeaksDecoy.add(allPeaksDecoyTmp.get(i)); allPeaksDecoyTmp.remove(i); } DefaultDecoySpectrum s=new DefaultDecoySpectrum(inputGraph.getParent(), allPeaksDecoy); return s; } }
3,585
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
RandomPeaksConstructor.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/decoytreeconstructors/RandomPeaksConstructor.java
package de.unijena.bioinf.decoy.model.decoytreeconstructors; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.decoy.decoytrees.DecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; public class RandomPeaksConstructor extends DefaultDecoyTreeConstructor implements DecoySpectrumConstructor{ static public final String methodNameLong="RandomPeaks"; Random r = new Random(); public RandomPeaksConstructor(ParametersDecoySpectrumConstruction p) { super(p); } public String getMethodNameLong(){ return methodNameLong; } // public DecoySpectrum getDecoySpectrum(){ // List<double[]> allPeaksDecoy=new ArrayList<double[]>(); // DecoyTreeVertex root=inputGraph.getRoot(); // allPeaksDecoy.add(new double[]{root.mz,root.intensity}); // // List<Graph> allGraphs=new ArrayList<Graph>(); // allGraphs.addAll(p.getAllGraphsInOriginal().values()); // while(allPeaksDecoy.size()<inputGraph.getVertices().size()){ // int i=r.nextInt(allGraphs.size()); // Graph currGraph=allGraphs.get(i); // DefaultDecoyTree dt=new DefaultDecoyTree(currGraph); // int i2=r.nextInt(dt.getVertices().size()); // double mass=dt.getVertices().get(i2).mz; // if(mass<root.mz){ // boolean alreadyAdded=false; // double error=Utils.getAbsoluteErrorForMass(mass, p.ppm, p.ae); // for(double d[]:allPeaksDecoy){ // if(Math.abs(mass-d[0])<error)alreadyAdded=true; // } // if(!alreadyAdded)allPeaksDecoy.add(new double[]{mass, dt.getVertices().get(i2).intensity}); // } // } public DecoySpectrum getDecoySpectrum(){ List<double[]> allPeaksDecoy=new ArrayList<double[]>(); DecoyTreeVertex root=inputGraph.getRoot(); allPeaksDecoy.add(new double[]{root.mz,root.intensity}); List<List<double[]>> allPeaks=new ArrayList<List<double[]>>(); allPeaks.addAll(p.getAllPeaksInOriginal().values()); while(allPeaksDecoy.size()<inputGraph.getVertices().size()){ int i=r.nextInt(allPeaks.size()); List<double[]> currPeaks=allPeaks.get(i); int i2=r.nextInt(currPeaks.size()); double mass=currPeaks.get(i2)[0]; if(mass<root.mz){ boolean alreadyAdded=false; double error=Utils.getAbsoluteErrorForMass(mass, p.ppm, p.ae); for(double d[]:allPeaksDecoy){ if(Math.abs(mass-d[0])<error)alreadyAdded=true; } if(!alreadyAdded)allPeaksDecoy.add(new double[]{mass, currPeaks.get(i2)[1]}); } } // List<double[]> allPeaksDB=getAllPeaksFromDB(inputGraph.getRoot().mz); // for(int i=0;i<inputGraph.getVertices().size()-1;i++){ // int index=r.nextInt(allPeaksDB.size()); // allPeaksDecoy.add(allPeaksDB.get(index)); // double addedMass=allPeaksDB.get(index)[0]; // Iterator<double[]> it=allPeaksDB.iterator(); // while(it.hasNext()){ // if(Double.compare(it.next()[0],addedMass)==0)it.remove(); // } // } DefaultDecoySpectrum s=new DefaultDecoySpectrum(inputGraph.getParent(), allPeaksDecoy); return s; } List<double[]> getAllPeaksFromDB(double maxMass){ List<double[]> peaks=new ArrayList<double[]>(); for(Graph g:p.getAllGraphsInOriginal().values()){ DefaultDecoyTree dt=new DefaultDecoyTree(g); peaks.addAll(dt.getPeaks(maxMass)); } return peaks; } }
3,642
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
DefaultDecoyFileConstructor.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/decoytreeconstructors/DefaultDecoyFileConstructor.java
package de.unijena.bioinf.decoy.model.decoytreeconstructors; import java.util.ArrayList; import java.util.List; import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.decoy.decoytrees.DecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; public class DefaultDecoyFileConstructor extends DefaultDecoyTreeConstructor implements DecoySpectrumConstructor{ static public final String methodNameLong="Original"; public DefaultDecoyFileConstructor(ParametersDecoySpectrumConstruction p){ super(p); } public String getMethodNameLong(){ return methodNameLong; } public void setOriginalTree(Graph g){ this.inputGraph=new DefaultDecoyTree(g); } public DecoySpectrum getDecoySpectrum(){ MolecularFormula root=null; List<double[]> peaks=new ArrayList<double[]>(); for(DecoyTreeVertex v:inputGraph.getVertices()){ peaks.add(new double[]{v.mz,v.intensity}); if(v.mf!=null&&(root==null||root.getMass()<v.mf.getMass()))root=v.mf; } return new DefaultDecoySpectrum(root, peaks); } }
1,339
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
DecoySpectrumConstructor.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/decoytreeconstructors/DecoySpectrumConstructor.java
package de.unijena.bioinf.decoy.model.decoytreeconstructors; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.decoy.decoytrees.DecoySpectrum; public interface DecoySpectrumConstructor { static public final String methodNameLong=null; public DecoySpectrum getDecoySpectrum(); public void setOriginalTree(Graph g); public String getMethodNameLong(); }
395
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
DefaultDecoyTreeConstructor.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/decoytreeconstructors/DefaultDecoyTreeConstructor.java
package de.unijena.bioinf.decoy.model.decoytreeconstructors; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.decoy.decoytrees.DecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; public class DefaultDecoyTreeConstructor implements DecoySpectrumConstructor{ static public final String methodNameLong="Original"; public final ParametersDecoySpectrumConstruction p; public Graph originalGraph=null; public DefaultDecoyTree inputGraph=null; public DefaultDecoyTreeConstructor(ParametersDecoySpectrumConstruction p){ this.p=p; } public String getMethodNameLong(){ return methodNameLong; } public void setOriginalTree(Graph g){ this.originalGraph=g; this.inputGraph=new DefaultDecoyTree(g); } public DecoySpectrum getDecoySpectrum(){ if(originalGraph.getRoot()==null)return new DefaultDecoySpectrum(inputGraph.getParent(), inputGraph.getOriginalPeaks()); return new DefaultDecoyTree(inputGraph); } }
1,144
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
RerootDecoyTreeConstructor.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/decoytreeconstructors/RerootDecoyTreeConstructor.java
package de.unijena.bioinf.decoy.model.decoytreeconstructors; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TreeMap; import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.babelms.dot.Vertex; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.decoy.model.DecoyTreeEdge; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; public class RerootDecoyTreeConstructor extends DefaultDecoyTreeConstructor implements DecoySpectrumConstructor{ static public final String methodNameLong="Reroot"; Random r = new Random(); double minMass; public RerootDecoyTreeConstructor(ParametersDecoySpectrumConstruction p){ super(p); this.minMass=p.getMinMass(); } public String getMethodNameLong(){ return methodNameLong; } public DefaultDecoyTree getDecoySpectrum(){ List<DefaultDecoyTree> decoyTrees=new ArrayList<DefaultDecoyTree>(); MolecularFormula parentMF=inputGraph.getRoot().getMolecularFormulaFromLabel(); for(Vertex v:inputGraph.getVertices()){ if(v!=inputGraph.getRoot()){ DefaultDecoyTree decoyTree=new DefaultDecoyTree(inputGraph); DecoyTreeVertex newRoot=decoyTree.getVertex(v.getName()); double rootIntensity=decoyTree.getRoot().intensity; // decoyTree.getRoot().intensity=newRoot.intensity; newRoot.intensity=rootIntensity; labelRecursive(decoyTree, newRoot, parentMF, null); decoyTrees.add(decoyTree); } } DefaultDecoyTree dt=getRandomDecoyTree(decoyTrees,r, minMass); rearrangeImpossibleNodes(dt, r, minMass); return dt; } public static double getProbabilityOfRearrangements(DefaultDecoyTree dt, double minMass){ return 1.0/(getNumberOfRearrangements(dt, minMass)+1); } public static int getNumberOfRearrangements(DefaultDecoyTree dt, double minMass){ int rearrangements=0; for(DecoyTreeVertex fragment:dt.getVertices()){ if(fragment.mf.shouldBeRearranged(minMass))rearrangements++; } return rearrangements; } public static void labelRecursive(DefaultDecoyTree dt, DecoyTreeVertex v, MolecularFormula mf, DecoyTreeEdge excludeEdge){ v.mf=mf; v.getProperties().put("label",mf.toString()); for(DecoyTreeEdge e:dt.getIncommingEdgesFor(v)){ if(e!=excludeEdge){ e.redirect(); } } for(DecoyTreeEdge e:dt.getOutgoingEdgesFor(v)){ if(e!=excludeEdge){ MolecularFormula mfChild=MolecularFormula.parse(mf.toString()); MolecularFormula mfLoss=e.getMolecularFormulaFromLabel(); mfChild=mfChild.subtract(mfLoss); labelRecursive(dt, dt.getVertex(e.getTail()), mfChild, e); } } } public static void rearrangeImpossibleNodes(DefaultDecoyTree dt, Random r, double minMass) { List<DecoyTreeVertex> verticesToRearrange=new ArrayList<DecoyTreeVertex>(); List<DecoyTreeVertex> allVertices=new ArrayList<DecoyTreeVertex>(); for(DecoyTreeVertex v:dt.getVertices()){ allVertices.add(v); if(v.mf.shouldBeRearranged(minMass)){ verticesToRearrange.add(v); } } for(DecoyTreeVertex vtr:verticesToRearrange){ List<DecoyTreeVertex> possibleParentVertices=new ArrayList<DecoyTreeVertex>(); List<MolecularFormula> newChildMolecularFormula=new ArrayList<MolecularFormula>(); List<DecoyTreeEdge> incommingEdges=dt.getIncommingEdgesFor(vtr); if(incommingEdges.size()!=0){ DecoyTreeEdge childE=incommingEdges.get(0); for(DecoyTreeVertex v:allVertices){ MolecularFormula newVertexMF=v.mf.subtract(childE.mf); if(!newVertexMF.shouldBeRearranged(minMass)){ //TODO: consider doubled peaks //boolean mfExists=false; //for(DecoyTreeVertex equalMF:allVertices){ //if(equalMF.mf.equals(newVertexMF))mfExists=true; //} //if(!mfExists){ possibleParentVertices.add(v); newChildMolecularFormula.add(newVertexMF); //} } } int choice=r.nextInt(possibleParentVertices.size()); DecoyTreeVertex parentV=possibleParentVertices.get(choice); childE.setHead(parentV.getName()); vtr.mf=newChildMolecularFormula.get(choice); vtr.getProperties().put("label",vtr.mf.toString()); } } } public static DefaultDecoyTree getRandomDecoyTree(List<DefaultDecoyTree> decoyTrees, Random r, double minMass){ double rand=r.nextDouble(); double sum=0; for(DefaultDecoyTree dt:decoyTrees){ sum+=getProbabilityOfRearrangements(dt, minMass); } double add=0; DefaultDecoyTree result=null; for(DefaultDecoyTree dt:decoyTrees){ add+=getProbabilityOfRearrangements(dt, minMass)/sum; if(add>=rand){ result=dt; break; } } return result; } }
5,097
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
ConditionalFastConstructor.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/decoytreeconstructors/ConditionalFastConstructor.java
package de.unijena.bioinf.decoy.model.decoytreeconstructors; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.decoy.decoytrees.DecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; public class ConditionalFastConstructor extends DefaultDecoyTreeConstructor implements DecoySpectrumConstructor{ // static private TreeMap<Double, List<Graph>> m=null; static private TreeMap<Double, List<List<double[]>>> m=null; static public final String methodNameLong="ConditionalFast"; Random r = new Random(); public ConditionalFastConstructor(ParametersDecoySpectrumConstruction p) { super(p); } public String getMethodNameLong(){ return methodNameLong; } // public DecoySpectrum getDecoySpectrum(){ // if(m==null){ // m=new TreeMap<Double, List<Graph>>(); // for(Graph g:p.getAllGraphsInOriginal().values()){ // List<double[]> peaks=DefaultDecoyTree.getPeaksIncludingMax(g,Double.POSITIVE_INFINITY); // for(double[] p:peaks){ // if(!m.containsKey(p[0]))m.put(p[0],new ArrayList<Graph>()); // m.get(p[0]).add(g); // } // } // } // // List<double[]> allPeaksDecoy=new ArrayList<double[]>(); // DecoyTreeVertex root=inputGraph.getRoot(); // // List<double[]> currentPeaks=new ArrayList<double[]>(); // currentPeaks.add(new double[]{root.mz,root.intensity}); // int size=inputGraph.getVertices().size(); // for(int i=0;i<size;i++){ // System.out.println(i+" of "+size); // int index=r.nextInt(currentPeaks.size()); // allPeaksDecoy.add(currentPeaks.get(index)); // double addedMass=currentPeaks.get(index)[0]; // currentPeaks.remove(index); // // List<double[]> peaksTmp=new ArrayList<double[]>(); // double error=Utils.getAbsoluteErrorForMass(addedMass, this.p.ppm, this.p.ae); // // SortedMap<Double, List<Graph>> mSub=m.subMap(m.ceilingKey(addedMass-error), true, m.floorKey(addedMass+error), true); // List<Graph> graphsSub=new ArrayList<Graph>(); // for(List<Graph> x:mSub.values())graphsSub.addAll(x); // boolean found=false; // List<double[]> peaks=new ArrayList<double[]>(); // while(!found&&graphsSub.size()>0){ // index=r.nextInt(graphsSub.size()); // Graph g=graphsSub.get(index); // peaks=DefaultDecoyTree.getPeaksIncludingMax(g,root.mz); // if(peaks.size()>0)found=true; // graphsSub.remove(index); // } // peaksTmp.addAll(peaks); // for(int t=0;t<Math.min(5,peaksTmp.size());t++){ // index=r.nextInt(peaksTmp.size()); // currentPeaks.add(peaksTmp.get(index)); // peaksTmp.remove(index); // } // } // // Set<Double> masses=new HashSet<Double>(); // Iterator<double[]> it=allPeaksDecoy.iterator(); // while(it.hasNext()){ // double mass=Math.round(it.next()[0]*1000000)/1000000.0; // boolean added=masses.add(mass); // if(!added)it.remove(); // } // // List<Graph> allGraphs=new ArrayList<Graph>(); // allGraphs.addAll(p.getAllGraphsInOriginal().values()); // while(allPeaksDecoy.size()<inputGraph.getVertices().size()){ // int i=r.nextInt(allGraphs.size()); // Graph currGraph=allGraphs.get(i); // DefaultDecoyTree dt=new DefaultDecoyTree(currGraph); // int i2=r.nextInt(dt.getVertices().size()); // double mass=dt.getVertices().get(i2).mz; // if(mass<root.mz){ // boolean alreadyAdded=false; // double error=Utils.getAbsoluteErrorForMass(mass, p.ppm, p.ae); // for(double d[]:allPeaksDecoy){ // if(Math.abs(mass-d[0])<error)alreadyAdded=true; // } // if(!alreadyAdded)allPeaksDecoy.add(new double[]{mass, dt.getVertices().get(i2).intensity}); // } // } // // DefaultDecoySpectrum s=new DefaultDecoySpectrum(inputGraph.getParent(), allPeaksDecoy); // return s; // } public static void setM(ParametersDecoySpectrumConstruction p){ if(m==null){ m=new TreeMap<Double, List<List<double[]>>>(); for(List<double[]> peaks:p.getAllPeaksInOriginal().values()){ for(double[] peak:peaks){ if(!m.containsKey(peak[0]))m.put(peak[0],new ArrayList<List<double[]>>()); m.get(peak[0]).add(peaks); } } } } public DecoySpectrum getDecoySpectrum(){ if(m==null){ setM(p); } List<double[]> allPeaksDecoy=new ArrayList<double[]>(); DecoyTreeVertex root=inputGraph.getRoot(); List<double[]> currentPeaks=new ArrayList<double[]>(); currentPeaks.add(new double[]{root.mz,root.intensity}); int size=inputGraph.getVertices().size(); for(int i=0;i<size;i++){ System.out.println(i+" of "+size); int index=r.nextInt(currentPeaks.size()); allPeaksDecoy.add(currentPeaks.get(index)); double addedMass=currentPeaks.get(index)[0]; currentPeaks.remove(index); List<double[]> peaksTmp=new ArrayList<double[]>(); double error=Utils.getAbsoluteErrorForMass(addedMass, this.p.ppm, this.p.ae); SortedMap<Double, List<List<double[]>>> mSub=m.subMap(m.ceilingKey(addedMass-error), true, m.floorKey(addedMass+error), true); List<List<double[]>> peaksSub=new ArrayList<List<double[]>>(); for(List<List<double[]>> x:mSub.values())peaksSub.addAll(x); boolean found=false; List<double[]> peaks=new ArrayList<double[]>(); while(!found&&peaksSub.size()>0){ index=r.nextInt(peaksSub.size()); List<double[]> g=peaksSub.get(index); for(double[] d:g)if(d[0]<=root.mz)peaks.add(d); if(peaks.size()>0)found=true; peaksSub.remove(index); } peaksTmp.addAll(peaks); for(int t=0;t<Math.min(5,peaksTmp.size());t++){ index=r.nextInt(peaksTmp.size()); currentPeaks.add(peaksTmp.get(index)); peaksTmp.remove(index); } } Set<Double> masses=new HashSet<Double>(); Iterator<double[]> it=allPeaksDecoy.iterator(); while(it.hasNext()){ double mass=Math.round(it.next()[0]*1000000)/1000000.0; boolean added=masses.add(mass); if(!added)it.remove(); } List<List<double[]>> allPeaks=new ArrayList<List<double[]>>(); allPeaks.addAll(p.getAllPeaksInOriginal().values()); while(allPeaksDecoy.size()<inputGraph.getVertices().size()){ int i=r.nextInt(allPeaks.size()); List<double[]> currPeaks=allPeaks.get(i); int i2=r.nextInt(currPeaks.size()); double mass=currPeaks.get(i2)[0]; if(mass<root.mz){ boolean alreadyAdded=false; double error=Utils.getAbsoluteErrorForMass(mass, p.ppm, p.ae); for(double d[]:allPeaksDecoy){ if(Math.abs(mass-d[0])<error)alreadyAdded=true; } if(!alreadyAdded)allPeaksDecoy.add(new double[]{mass, currPeaks.get(i2)[1]}); } } DefaultDecoySpectrum s=new DefaultDecoySpectrum(inputGraph.getParent(), allPeaksDecoy); return s; } public static List<double[]> getAllPeaksFromDB(double maxMass, Collection<Graph> graphsInOriginalDB){ List<double[]> result=new ArrayList<double[]>(); for(Graph g:graphsInOriginalDB){ DefaultDecoyTree dt=new DefaultDecoyTree(g); List<double[]> peaks=dt.getPeaksIncludingMax(maxMass); result.addAll(peaks); } return result; } }
7,693
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
RandomTreeDecoyTreeConstructor.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/decoy/model/decoytreeconstructors/RandomTreeDecoyTreeConstructor.java
package de.unijena.bioinf.decoy.model.decoytreeconstructors; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TreeMap; import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula; import de.unijena.bioinf.babelms.dot.Edge; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.babelms.dot.Vertex; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.decoy.model.DecoyTreeEdge; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; public class RandomTreeDecoyTreeConstructor extends DefaultDecoyTreeConstructor implements DecoySpectrumConstructor{ static public final String methodNameLong="RandomTree"; Random r = new Random(); double minMass; public RandomTreeDecoyTreeConstructor(ParametersDecoySpectrumConstruction p){ super(p); this.minMass=p.getMinMass(); } public String getMethodNameLong(){ return methodNameLong; } // public DefaultDecoyTree getDecoySpectrum(){ // List<Graph> allGraphs=new ArrayList<Graph>(); // allGraphs.addAll(p.getAllGraphsInOriginal().values()); // List<MolecularFormula> mfs=new ArrayList<MolecularFormula>(); // // for(Graph t:allGraphs){ // DefaultDecoyTree g=new DefaultDecoyTree(t); // for(DecoyTreeEdge e:g.getEdges())mfs.add(e.mf); // } // // DefaultDecoyTree decoyTree=new DefaultDecoyTree(inputGraph); // Random r=new Random(); // List<DecoyTreeEdge> currentEdges=decoyTree.getOutgoingEdgesFor(decoyTree.getRoot()); // while(!currentEdges.isEmpty()){ // DecoyTreeEdge e=currentEdges.get(0); // DecoyTreeVertex vH=null; // List<MolecularFormula> mfsTmp=new ArrayList<MolecularFormula>(); // while(mfsTmp.isEmpty()){ // if(vH==null){ // vH=decoyTree.getVertex(e.getHead()); // }else{ // System.out.print("rearrangement "+e.toString()); // vH=decoyTree.getVertex(decoyTree.getIncommingEdgesFor(vH.getName()).get(0).getHead()); // System.out.println(" to "+vH.getName()); // } // MolecularFormula mfH=vH.mf; // for(MolecularFormula mf:mfs)if(mfH.isSubtractable(mf))mfsTmp.add(mf); // // } // MolecularFormula mf=mfsTmp.get(r.nextInt(mfsTmp.size())); // e.mf=mf; // e.setHead(vH.getName()); // decoyTree.getVertex(e.getTail()).mf=vH.mf.subtract(mf); // currentEdges.remove(e); // for(DecoyTreeEdge newE:decoyTree.getOutgoingEdgesFor(decoyTree.getVertex(e.getTail())))currentEdges.add(newE); // } // // if(!currentEdges.isEmpty())return null; // // return decoyTree; // } public DefaultDecoyTree getDecoySpectrum(){ List<Graph> allGraphs=new ArrayList<Graph>(); allGraphs.addAll(p.getAllGraphsInOriginal().values()); List<MolecularFormula> mfs=new ArrayList<MolecularFormula>(); for(Graph t:allGraphs){ for(Edge e:t.getEdges()){ MolecularFormula mf=MolecularFormula.parse(e.getProperties().get("label").replaceAll("\\\\n.*","")); mfs.add(mf); } } DefaultDecoyTree decoyTree=new DefaultDecoyTree(inputGraph); Random r=new Random(); List<DecoyTreeEdge> currentEdges=decoyTree.getOutgoingEdgesFor(decoyTree.getRoot()); while(!currentEdges.isEmpty()){ DecoyTreeEdge e=currentEdges.get(0); DecoyTreeVertex vH=null; List<MolecularFormula> mfsTmp=new ArrayList<MolecularFormula>(); while(mfsTmp.isEmpty()){ if(vH==null){ vH=decoyTree.getVertex(e.getHead()); }else{ System.out.print("rearrangement "+e.toString()); vH=decoyTree.getVertex(decoyTree.getIncommingEdgesFor(vH.getName()).get(0).getHead()); System.out.println(" to "+vH.getName()); } MolecularFormula mfH=vH.mf; for(MolecularFormula mf:mfs)if(mfH.isSubtractable(mf))mfsTmp.add(mf); } MolecularFormula mf=mfsTmp.get(r.nextInt(mfsTmp.size())); e.mf=mf; e.setHead(vH.getName()); decoyTree.getVertex(e.getTail()).mf=vH.mf.subtract(mf); currentEdges.remove(e); for(DecoyTreeEdge newE:decoyTree.getOutgoingEdgesFor(decoyTree.getVertex(e.getTail())))currentEdges.add(newE); } if(!currentEdges.isEmpty())return null; return decoyTree; } }
4,442
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
SpectrumComparator.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/pvalue/SpectrumComparator.java
package de.unijena.bioinf.pvalue; import java.util.Comparator; class SpectrumComparator implements Comparator<double[]>{ @Override public int compare(double[] o1, double[] o2) { return Double.compare(o1[0], o2[0]); } }
239
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
SisterSpectrumGeneratorRandomPeaks.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/pvalue/SisterSpectrumGeneratorRandomPeaks.java
package de.unijena.bioinf.pvalue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Map.Entry; import java.util.TreeMap; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.babelms.dot.Vertex; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.decoy.model.decoytreeconstructors.ConditionalPeaksConstructor; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.CHARGE; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.DATASET; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.METHOD; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.POSTPROCESS; public class SisterSpectrumGeneratorRandomPeaks{ Random r=new Random(); int numberPeaks; Map<Double,List<double[]>> conditionalPeaksFromDB; List<double[]> allPeaksFromDB; public SisterSpectrumGeneratorRandomPeaks(int numberPeaks, ParametersDecoySpectrumConstruction p){ this.numberPeaks=numberPeaks; this.conditionalPeaksFromDB=ConditionalPeaksConstructor.getAllConditionalPeaksFromDB(Double.MAX_VALUE,p.getAllGraphsInOriginal().values()); this.allPeaksFromDB=ConditionalPeaksConstructor.getAllPeaksFromDB(Double.MAX_VALUE,p.getAllGraphsInOriginal().values()); } public List<double[]> getStartSpectrum(){ List<double[]> allPeaksFromDBTmp=new ArrayList<double[]>(allPeaksFromDB); List<double[]> allPeaksDecoy=new ArrayList<double[]>(); for(int i=0;i<numberPeaks;i++){ int rand=r.nextInt(allPeaksFromDBTmp.size()); double[] nextPeak=allPeaksFromDBTmp.get(rand); allPeaksDecoy.add(nextPeak); Iterator<double[]> it=allPeaksFromDBTmp.iterator(); while(it.hasNext())if(Double.compare(it.next()[0],nextPeak[0])==0)it.remove(); } Collections.sort(allPeaksDecoy,new SpectrumComparator()); return allPeaksDecoy; } public List<double[]> getSisterSpectrum(List<double[]> originalSpectrum){ List<double[]> spectrum=new ArrayList<double[]>(originalSpectrum); int rand=r.nextInt(spectrum.size()); spectrum.remove(rand); List<double[]> allPeaksFromDBTmp=new ArrayList<double[]>(allPeaksFromDB); boolean added=false; while(!added){ rand=r.nextInt(allPeaksFromDBTmp.size()); double[] nextPeak=allPeaksFromDBTmp.get(rand); boolean alreadyExists=false; for(double[] d:spectrum) if(Double.compare(d[0],nextPeak[0])==0)alreadyExists=true; if(!alreadyExists){ spectrum.add(nextPeak); added=true; } } Collections.sort(spectrum, new SpectrumComparator()); return spectrum; } }
3,162
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
SisterSpectrumGeneratorConditionalPeaks.java
/FileExtraction/Java_unseen/boecker-lab_passatuto/src/de/unijena/bioinf/pvalue/SisterSpectrumGeneratorConditionalPeaks.java
package de.unijena.bioinf.pvalue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Map.Entry; import java.util.TreeMap; import de.unijena.bioinf.babelms.dot.Graph; import de.unijena.bioinf.babelms.dot.Vertex; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoySpectrum; import de.unijena.bioinf.decoy.decoytrees.DefaultDecoyTree; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction; import de.unijena.bioinf.decoy.model.DecoyTreeVertex; import de.unijena.bioinf.decoy.model.decoytreeconstructors.ConditionalPeaksConstructor; import de.unijena.bioinf.deocy.Utils; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.CHARGE; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.DATASET; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.METHOD; import de.unijena.bioinf.msblast.ParametersDecoySpectrumConstruction.POSTPROCESS; public class SisterSpectrumGeneratorConditionalPeaks{ Random r=new Random(); double[] parentPeak; int numberPeaks; Map<Double,List<double[]>> conditionalPeaksFromDB; List<double[]> allPeaksFromDB; public SisterSpectrumGeneratorConditionalPeaks(double[] parentPeak, int numberPeaks, ParametersDecoySpectrumConstruction p){ this.parentPeak=parentPeak; this.numberPeaks=numberPeaks; this.conditionalPeaksFromDB=ConditionalPeaksConstructor.getAllConditionalPeaksFromDB(parentPeak[0],p.getAllGraphsInOriginal().values()); this.allPeaksFromDB=ConditionalPeaksConstructor.getAllPeaksFromDB(parentPeak[0],p.getAllGraphsInOriginal().values()); } // public static void main(String[] args){ // // Locale.setDefault(Locale.US); // // Random r=new Random(); // int numberPeaks=10; // // ParametersDecoySpectrumConstruction p=new ParametersDecoySpectrumConstruction(CHARGE.POS, DATASET.AGILENT, METHOD.ORIGINAL, Arrays.asList(new POSTPROCESS[]{})); // // List<double[]> allPeaks=new ArrayList<double[]>(); // Collection<Graph> graphs=p.getAllGraphsInOriginalDB().values(); // for(Graph g:graphs){ // for(Vertex v:g.getVertices()){ // DecoyTreeVertex dtv=new DecoyTreeVertex(v); // allPeaks.add(new double[]{dtv.mf.getMass(),dtv.intensity}); // } // } // double[] parentPeak=allPeaks.get(r.nextInt(allPeaks.size())); // // // SisterSpectrumGenerator g=new SisterSpectrumGenerator(parentPeak, numberPeaks, p); // List<double[]> startSpectrum=g.getStartSpectrum(); // List<double[]> sisterSpectrum=g.getSisterSpectrum(startSpectrum); // } public List<double[]> getStartSpectrum(){ // Map<Double,List<double[]>> conditionalPeaksFromDBTmp=new HashMap<Double, List<double[]>>(); // for(Entry<Double, List<double[]>> e:conditionalPeaksFromDB.entrySet()){ // List<double[]> newList=new ArrayList<double[]>(e.getValue()); // conditionalPeaksFromDBTmp.put(e.getKey(), newList); // } // // List<double[]> allPeaksDecoy=new ArrayList<double[]>(); // allPeaksDecoy.add(parentPeak); // // for(int i=0;i<numberPeaks-1;i++){ // // List<double[]> currentPeaks=new ArrayList<double[]>(); // for(double[] p:allPeaksDecoy){ // if(conditionalPeaksFromDBTmp.get(p[0])!=null){ // for(double[] p2:conditionalPeaksFromDBTmp.get(p[0])){ // if(Double.compare(parentPeak[0],p2[0])!=0)currentPeaks.add(p2); // } // } // } // // if(currentPeaks.isEmpty()){ // int index=r.nextInt(conditionalPeaksFromDBTmp.values().size()); // List<double[]> tmp=(List<double[]>)conditionalPeaksFromDBTmp.values().toArray()[index]; // index=r.nextInt(tmp.size()); // currentPeaks.add(tmp.get(index)); // } // // int index=r.nextInt(currentPeaks.size()); // allPeaksDecoy.add(currentPeaks.get(index)); // double addedMass=currentPeaks.get(index)[0]; // for(List<double[]> peaks:conditionalPeaksFromDBTmp.values()){ // Iterator<double[]> it=peaks.iterator(); // while(it.hasNext()){ // if(Double.compare(it.next()[0],addedMass)==0)it.remove(); // } // } // } // Collections.sort(allPeaksDecoy,new SpectrumComparator()); // return allPeaksDecoy; List<double[]> allPeaksFromDBTmp=new ArrayList<double[]>(allPeaksFromDB); List<double[]> allPeaksDecoy=new ArrayList<double[]>(); allPeaksDecoy.add(parentPeak); Iterator<double[]> it=allPeaksFromDBTmp.iterator(); while(it.hasNext())if(Double.compare(it.next()[0],parentPeak[0])==0)it.remove(); for(int i=0;i<numberPeaks-1;i++){ int rand=r.nextInt(allPeaksFromDBTmp.size()); double[] nextPeak=allPeaksFromDBTmp.get(rand); allPeaksDecoy.add(nextPeak); it=allPeaksFromDBTmp.iterator(); while(it.hasNext())if(Double.compare(it.next()[0],nextPeak[0])==0)it.remove(); } Collections.sort(allPeaksDecoy,new SpectrumComparator()); return allPeaksDecoy; } public List<double[]> getSisterSpectrum(List<double[]> originalSpectrum){ List<double[]> spectrum=new ArrayList<double[]>(originalSpectrum); Collections.sort(spectrum, new SpectrumComparator()); Map<double[],Integer> deletingOnePeak=new HashMap<double[],Integer>(); int allN=0; for(int i=0;i<spectrum.size()-1;i++){ double[] deletedPeak=spectrum.get(i); int n=0; for(int j=0;j<spectrum.size();j++){ if(i!=j){ double[] currentPeak=spectrum.get(j); List<double[]> condPeaks=conditionalPeaksFromDB.get(currentPeak[0]); if(condPeaks!=null){ for(double[] p:condPeaks) if(Double.compare(p[0],deletedPeak[0])==0) n++; } } } deletingOnePeak.put(deletedPeak,n); allN+=n; } int k=r.nextInt(allN); int i=0; double[] deletedPeak=null; for(Entry<double[], Integer> e:deletingOnePeak.entrySet()){ if(i+e.getValue()>k){ deletedPeak=e.getKey(); break; }else{ i+=e.getValue(); } } Iterator<double[]> iteratorSpectrum=spectrum.iterator(); while(iteratorSpectrum.hasNext()){ if(iteratorSpectrum.next()==deletedPeak)iteratorSpectrum.remove(); } List<double[]> currentPeaks=new ArrayList<double[]>(); for(double[] p:spectrum){ if(conditionalPeaksFromDB.get(p[0])!=null) currentPeaks.addAll(conditionalPeaksFromDB.get(p[0])); } currentPeaks.addAll(allPeaksFromDB); boolean added=false; while(!added){ int index=r.nextInt(currentPeaks.size()); double[] peak=currentPeaks.get(index); boolean alreadyExists=false; for(double[] s:spectrum)if(Double.compare(s[0],peak[0])==0)alreadyExists=true; if(!alreadyExists){ spectrum.add(peak); added=true; } } Collections.sort(spectrum, new SpectrumComparator()); return spectrum; } }
6,997
Java
.java
boecker-lab/passatuto
9
1
0
2017-01-20T09:48:17Z
2017-01-20T10:23:52Z
AppTest.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/test/java/org/flashtool/AppTest.java
/* * This Java source file was generated by the Gradle 'init' task. */ package org.flashtool; import org.testng.annotations.*; import static org.testng.Assert.*; import org.flashtool.gui.Main; public class AppTest { @Test public void appHasAGreeting() { Main classUnderTest = new Main(); assertNotNull(classUnderTest, "app should have a greeting"); } }
383
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
APKUtility.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/adb/APKUtility.java
package org.flashtool.jna.adb; import java.io.File; import lombok.extern.slf4j.Slf4j; import net.dongliu.apk.parser.ApkFile; @Slf4j public class APKUtility { public static String getPackageName(String apkname) throws Exception { try (ApkFile apkFile = new ApkFile(new File(apkname))) { return apkFile.getApkMeta().getPackageName(); } } }
355
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
FastbootUtility.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/adb/FastbootUtility.java
package org.flashtool.jna.adb; import java.util.Enumeration; import java.util.Scanner; import java.util.Vector; import org.flashtool.system.OS; import org.flashtool.system.ProcessBuilderWrapper; import org.flashtool.system.RunOutputs; import lombok.extern.slf4j.Slf4j; @Slf4j public class FastbootUtility { private static String adbpath = OS.getPathAdb(); private static String fastbootpath = OS.getPathFastBoot(); public static void adbRebootFastboot() throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"reboot", "bootloader"},false); } public static Enumeration<String> getDevices() { Vector<String> v = new Vector<String>(); try { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {fastbootpath, "devices"},false); Scanner sc = new Scanner(command.getStdOut()); while (sc.hasNextLine()) { String line = sc.nextLine(); if (!line.contains("????")) v.add(line.split("\t")[0]); } } catch (Exception e) { } return v.elements(); } public static RunOutputs hotBoot(String bootimg) throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {fastbootpath,"boot", bootimg},false); return command.getOutputs(); } public static RunOutputs flashBoot(String bootimg) throws Exception { ProcessBuilderWrapper pbd = new ProcessBuilderWrapper(new String[] {fastbootpath,"flash", "boot", bootimg},true); return pbd.getOutputs(); } public static RunOutputs flashSystem(String systemimg) throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {fastbootpath,"flash", "system", systemimg},false); return command.getOutputs(); } public static RunOutputs unlock(String key) throws Exception { log.info("Unlocking phone using key "+key); ProcessBuilderWrapper pbd = new ProcessBuilderWrapper(new String[] {fastbootpath,"-i", "0xfce","oem", "unlock","0x"+key },true); return pbd.getOutputs(); } public static void rebootDevice() throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {fastbootpath,"reboot"},false); } public static void rebootFastboot() throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {fastbootpath,"reboot-bootloader"},false); } public static void wipeDataCache() throws Exception { // currently there seems to be some issue executing this ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {fastbootpath,"-w"},false); } public static RunOutputs getDeviceInfo() throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {fastbootpath,"devices"},false); return command.getOutputs(); } public static RunOutputs getFastbootVerInfo() throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {fastbootpath,"-i", "0x0fce", "getvar", "version"},false); return command.getOutputs(); } public static void killFastbootWindows() { try { ProcessBuilderWrapper fastboot = new ProcessBuilderWrapper(new String[] {"taskkill", "/F", "/T", "/IM", "fastboot*"},false); } catch (Exception e) { } } }
3,212
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
AdbException.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/adb/AdbException.java
package org.flashtool.jna.adb; import lombok.extern.slf4j.Slf4j; @Slf4j public class AdbException extends Exception{ /** * */ private static final long serialVersionUID = 1L; public AdbException(String msg){ super(msg); } public AdbException(String msg, Throwable t){ super(msg,t); } }
326
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
AdbUtility.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/adb/AdbUtility.java
package org.flashtool.jna.adb; import java.io.ByteArrayInputStream; import java.io.File; import java.util.Enumeration; import java.util.HashSet; import java.util.Properties; import java.util.Scanner; import java.util.Vector; import org.flashtool.system.Devices; import org.flashtool.system.FTShell; import org.flashtool.system.GlobalConfig; import org.flashtool.system.OS; import org.flashtool.system.ProcessBuilderWrapper; import lombok.extern.slf4j.Slf4j; @Slf4j public class AdbUtility { static Properties build = new Properties(); static boolean rootnative=false; static boolean rootperms=false; private static String fsep = OS.getFileSeparator(); private static String shellpath = OS.getFolderCustom()+fsep+"shells"; private static String adbpath = OS.getPathAdb(); private static String shpath =""; public static void resetRoot() { rootnative=false; rootperms=false; } public static String getShellPath() { return shellpath; } public static void setShellPath(String path) { shellpath = path; } public static boolean exists(String path) { try { ProcessBuilderWrapper command; command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "ls -l "+path},false); return !command.getStdOut().toLowerCase().contains("no such file or directory") && !command.getStdOut().toLowerCase().contains("permission denied"); } catch (Exception e) { return false; } } public static boolean existsRoot(String path) { try { ProcessBuilderWrapper command; command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "su -c 'ls -l "+path+"'"},false); return !command.getStdOut().toLowerCase().contains("no such file or directory") && !command.getStdOut().toLowerCase().contains("permission denied"); } catch (Exception e) { return false; } } public static String getShPath(boolean force) { if (shpath==null || force) { try { if (exists("/system/flashtool/sh")) shpath="/system/flashtool/sh"; else { ProcessBuilderWrapper command1 = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "echo $0"},false); shpath = command1.getStdOut().trim(); } } catch (Exception e) { shpath = ""; } } log.debug("Default shell for scripts : "+shpath); return shpath; } public static boolean hasRootNative(boolean force) { try { if (!force && rootnative) return true; ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell","id"},false); rootnative=command.getStdOut().contains("uid=0"); } catch (Exception e) { } return rootnative; } public static void forward(String type,String local, String remote) throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"forward "+type.toUpperCase()+":"+local+" "+type.toUpperCase()+":"+remote},false); } public static HashSet<String> listSysApps() throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "ls /system/app/*apk"},false); String[] result = command.getStdOut().split("\n"); HashSet<String> set = new HashSet<String>(); for (int i=0;i<result.length;i++) { String apk = result[i].substring(result[i].lastIndexOf('/')+1); if (!apk.contains("No such file or directory")) set.add(apk.substring(0,apk.lastIndexOf(".apk")+4)); } command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "ls /system/app/*odex"},false); result = command.getStdOut().split("\n"); for (int i=0;i<result.length;i++) { String apk = result[i].substring(result[i].lastIndexOf('/')+1); if (!apk.contains("No such file or directory")) set.add(apk.substring(0,apk.lastIndexOf(".odex")+5)); } return set; } public static HashSet<String> listKernels() throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "find /system/kernel -name 'kernel.desc' -type f"},false); String[] result = command.getStdOut().split("\n"); HashSet<String> set = new HashSet<String>(); for (int i=0;i<result.length;i++) { int first = result[i].indexOf('/', 1); first = result[i].indexOf('/', first+1); int last = result[i].indexOf('/', first+1); set.add(result[i].substring(first+1,last)); } return set; } public static HashSet<String> listRecoveries() throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "find /system/recovery -name 'recovery.desc' -type f"},false); String[] result = command.getStdOut().split("\n"); HashSet<String> set = new HashSet<String>(); for (int i=0;i<result.length;i++) { int first = result[i].indexOf('/', 1); first = result[i].indexOf('/', first+1); int last = result[i].indexOf('/', first+1); set.add(result[i].substring(first+1,last)); } return set; } /*public static boolean isSystemMounted() throws Exception { if (systemmounted==null) { systemmounted = isMounted("/system"); } return systemmounted.booleanValue(); }*/ public static void init() { rootnative=false; rootperms=false; shpath=null; } public static boolean isMounted(String mountpoint) throws Exception { boolean result = false; ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "mount"},false); Scanner sc = new Scanner(command.getStdOut()); while (sc.hasNextLine()) { String line = sc.nextLine(); if (line.contains(mountpoint)) { result = true; } } return result; } public static boolean hasSU() { boolean result = true; try { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "type su"},false); Scanner sc = new Scanner(command.getStdOut()); while (sc.hasNextLine()) { String line = sc.nextLine(); if (line.toLowerCase().contains("not found")) { result = false; } } } catch (Exception e) { return false; } return result; } public static String getFilePerms(String file) { try { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "stat "+file},false); Scanner sc = new Scanner(command.getStdOut()); while (sc.hasNextLine()) { String line = sc.nextLine(); if (line.contains("Uid")) { return line; } } return " "; } catch (Exception e) { return " "; } } public static ByteArrayInputStream getBuildProp() throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "cat /system/build.prop"},false); return new ByteArrayInputStream(command.getStdOut().getBytes()); } public static boolean hasRootPerms() { if (hasRootNative(false)) return true; if (rootperms) return true; try { FTShell shell = new FTShell("checkperms"); String result=shell.runRoot(false); while (result.toLowerCase().contains("segmentation fault")) { Thread.sleep(10000); result=shell.runRoot(false); } rootperms=result.contains("uid=0"); return rootperms; } catch (Exception e) { return false; } } public static HashSet<String> ls(String basedir,String type) throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath+"shell", "find "+basedir+" -maxdepth 1 -type "+type},false); String[] result = command.getStdOut().split("\n"); HashSet<String> set = new HashSet<String>(); for (int i=0;i<result.length;i++) { if (result[i].substring(result[i].lastIndexOf('/')+1).length()>0 && !result[i].substring(result[i].lastIndexOf('/')+1).equals("/")) set.add(result[i].substring(result[i].lastIndexOf('/')+1)); } return set; } public static void pushExe(String source, String destfolder, String destname) throws Exception { AdbUtility.push(source, destfolder+"/"+destname); AdbUtility.run("chmod 755 "+destfolder+"/"+destname); } public static void uninstall(String apk, boolean silent) throws Exception { if (!silent) log.info("Uninstalling "+apk); ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"uninstall",apk},false); } public static void killServer() throws Exception { //log.info("Killing adb service"); if (OS.getName().equals("windows")) { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"kill-server"},false); } else { ProcessBuilderWrapper command3 = new ProcessBuilderWrapper(new String[] {adbpath,"kill-server"},false); ProcessBuilderWrapper command1 = new ProcessBuilderWrapper(new String[] {"killall","adb"},false); } } public static void startServer() throws Exception { log.info("Starting adb service"); ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"start-server"},false); } public static void push(String source, String destination) throws Exception { push(source, destination, true); } public static void restore(String source) throws Exception { File f = new File(source); if (!f.exists()) throw new AdbException(source+" : Not found"); ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"restore",f.getAbsolutePath()},false); if (command.getStatus()!=0) { throw new AdbException(command.getStdOut()+ " " + command.getStdErr()); } } public static void push(String source, String destination, boolean logging) throws Exception { File f = new File(source); if (!f.exists()) throw new AdbException(source+" : Not found"); if (logging) log.info("Pushing "+f.getAbsolutePath()+" to "+destination); else log.debug("Pushing "+f.getAbsolutePath()+" to "+destination); ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"push",f.getAbsolutePath(),destination},false); if (command.getStatus()!=0) { throw new AdbException(command.getStdOut()+ " " + command.getStdErr()); } } public static String getBusyboxVersion(String path) { try { ProcessBuilderWrapper command; if (isMounted("/system")) { command = new ProcessBuilderWrapper(new String[] {adbpath,"shell",path+"/busybox"},false); } else { command = new ProcessBuilderWrapper(new String[] {adbpath,"shell","/sbin/busybox"},false); } Scanner sc = new Scanner(command.getStdOut()); if (sc.hasNextLine()) { String line = sc.nextLine(); if (line.contains("BusyBox v1") && line.contains("multi-call")) return line; } return ""; } catch (Exception e) { return ""; } } public static void mount(String mountpoint,String options, String type) throws Exception { if (hasRootNative(false)) { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell","mount -o "+options+" -t "+type+" "+mountpoint},false); } } public static void umount(String mountpoint) throws Exception { if (hasRootNative(false)) { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "umount "+mountpoint},false); } } public static void pull(String source, String destination) throws Exception { pull(source,destination,true); } public static void pull(String source, String destination, boolean logging) throws Exception { if (logging) log.info("Pulling "+source+" to "+destination); else log.debug("Pulling "+source+" to "+destination); ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"pull",source, destination},false); if (command.getStatus()!=0) { throw new AdbException(command.getStdOut()+ " " + command.getStdErr()); } } public static String getKernelVersion(boolean hasbusybox) { try { String result = ""; if (!hasbusybox) { AdbUtility.push(Devices.getCurrent().getBusybox(false), GlobalConfig.getProperty("deviceworkdir")+"/busybox1",false); AdbUtility.run("chmod 755 "+GlobalConfig.getProperty("deviceworkdir")+"/busybox1"); result = run(GlobalConfig.getProperty("deviceworkdir")+"/busybox1 uname -r"); run("rm -r "+GlobalConfig.getProperty("deviceworkdir")+"/busybox1"); } else result = run("busybox uname -r"); return result; } catch (Exception e) { return ""; } } public static String run(FTShell shell, boolean debug) throws Exception { push(shell.getPath(),GlobalConfig.getProperty("deviceworkdir")+"/"+shell.getName(),false); if (debug) log.debug("Running "+shell.getName()); else log.info("Running "+shell.getName()); ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell", "sh "+GlobalConfig.getProperty("deviceworkdir")+"/"+shell.getName()+";exit $?"},false); if (command.getStdOut().contains("FTError")) throw new Exception(command.getStdErr()+" "+command.getStdOut()); return command.getStdOut(); } public static String run(String com, boolean debug) throws Exception { if (debug) log.debug("Running "+ com + " command"); else log.info("Running "+ com + " command"); ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"shell",com},false); return command.getStdOut().trim(); } public static String run(String com) throws Exception { return run(com,true); } public static String runRoot(FTShell shell) throws Exception { return runRoot(shell,true); } public static String runRoot(FTShell shell,boolean logging) throws Exception { FTShell s=new FTShell("sysrun"); s.save(); push(s.getPath(),GlobalConfig.getProperty("deviceworkdir")+"/sysrun",false); s.clean(); push(shell.getPath(),GlobalConfig.getProperty("deviceworkdir")+"/runscript",false); if (logging) log.info("Running "+shell.getName()+" as root thru sysrun"); else log.debug("Running "+shell.getName()+" as root thru sysrun"); ProcessBuilderWrapper command; if (rootnative) command=new ProcessBuilderWrapper(new String[] {adbpath,"shell", "sh "+GlobalConfig.getProperty("deviceworkdir")+"/sysrun"},false); else command=new ProcessBuilderWrapper(new String[] {adbpath,"shell", "su -c 'sh "+GlobalConfig.getProperty("deviceworkdir")+"/sysrun'"},false); return command.getStdOut(); } public static boolean Sysremountrw() throws Exception { log.info("Remounting system read-write"); FTShell shell = new FTShell("remount"); return !shell.runRoot(false).contains("FTError"); } public static void clearcache() throws Exception { log.info("Clearing dalvik cache and rebooting"); FTShell shell = new FTShell("clearcache"); shell.runRoot(false); } public static void install(String apk) throws Exception { log.info("Installing "+apk); ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"install", "\""+apk+"\""},false); if (command.getStdOut().contains("Failure")) { uninstall(APKUtility.getPackageName(apk),true); command = new ProcessBuilderWrapper(new String[] {adbpath,"install","\""+apk+"\""},false); if (command.getStdOut().contains("Failure")) { Scanner sc = new Scanner(command.getStdOut()); sc.nextLine(); log.error(sc.nextLine()); } } } public static void scanStatus() throws Exception { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"status-window"},false); } public static String getStatus() { try { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"get-state"},false); if (command.getStdErr().contains("unauthorized")) return "adb_unauthorized"; if (command.getStdErr().contains("error")) return "normal"; if (command.getStdOut().contains("device")) return "adb"; return "none"; } catch (Exception e) { return "none"; } } public static boolean isConnected() { try { log.debug("Testing if device is connected"); return AdbUtility.getDevices().hasMoreElements(); } catch (Exception e) { return false; } } /* public static boolean isConnected() { try { log.info("Searching Adb Device"); String res =Device.AdbId(); if (res.equals("ErrNotPlugged")) { MyLogger.error("Please plug your device with USB Debugging and Unknown sources on"); return false; } else if (res.equals("ErrDriverError")) { MyLogger.error("ADB drivers are not installed"); return false; } boolean connected = false; ProcessBuilderWrapper command = new ProcessBuilderWrapper(adbpath+" devices"); command.run(); String[] result = command.getStdOut().split("\n"); for (int i=1;i<result.length; i++) { connected=result[i].contains("device"); } if (!connected) { MyLogger.error("Please plug your device with USB Debugging and Unknown sources turned on"); } return connected; } catch (Exception e) { MyLogger.error("Please plug your device with USB Debugging and Unknown sources turned on"); return false; } }*/ public static Enumeration<String> getDevices() { Vector<String> v = new Vector<String>(); try { ProcessBuilderWrapper command = new ProcessBuilderWrapper(new String[] {adbpath,"devices"},false); Scanner sc = new Scanner(command.getStdOut()); while (sc.hasNextLine()) { String line = sc.nextLine(); if (!line.startsWith("List")) { String[] content=line.split("\t"); if (content[content.length-1].contains("device")) v.add(content[0]); } } } catch (Exception e) {} return v.elements(); } public static long rawBackup(String source, String destination) { String md5source = getMD5(source); String result=""; long transferred=0L; try { result = AdbUtility.run("su -c 'dd if="+source+" of="+destination+" && sync && sync && sync && sync && chmod 444 "+destination+"'"); } catch (Exception e) { } if (!result.contains("bytes transferred")) return 0L; Scanner sc = new Scanner(result); while(sc.hasNextLine()) { String line = sc.nextLine(); if (line.contains("bytes")) { transferred = Long.parseLong(line.split(" ")[0]); } } String md5destination = getMD5(destination); if (!md5source.equals(md5destination)) return 0L; return transferred; } public static long getSizeOf(String source) { String result = ""; try { result = AdbUtility.run("su -c 'busybox stat "+source+"'"); } catch (Exception e) { result = ""; } if (!result.contains("Size")) return 0L; Scanner sc = new Scanner(result); while (sc.hasNextLine()) { String line = sc.nextLine(); if (line.contains("Size")) { return Long.parseLong(line.substring(line.indexOf("Size"),line.indexOf("Blocks")).replace("Size:", "").trim()); } } return 0L; } public static String getMD5(String source) { try { String md5 = AdbUtility.run("su -c 'export PATH=$PATH:/data/local/tmp;busybox md5sum "+source+"'").split(" ")[0].toUpperCase().trim(); if (md5==null) return ""; if (md5.length()!=32) md5=""; return md5; } catch (Exception e) { return ""; } } public static void antiRic() { try { Scanner scan = new Scanner(AdbUtility.run("ps")); String path = ""; String pid = ""; while (scan.hasNextLine()) { String line = scan.nextLine(); if (line.contains("bin/ric")) { String[] fields = line.split("\\s+"); pid = fields[1]; path = fields[fields.length-1]; } } scan.close(); if (path.length()>0) { log.info("Stopping ric service"); AdbUtility.run("su -c 'mount -o remount,rw / && mv "+path+" "+path+"c && mount -o remount,ro / && kill -9 "+pid+"'"); log.info("ric service stopped successfully"); } } catch (Exception e) { } } }
19,482
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
JKernel32.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/win32/JKernel32.java
package org.flashtool.jna.win32; import java.io.IOException; import org.flashtool.flashsystem.io.USBFlashLinux; import org.flashtool.jna.linux.JUsb; import org.flashtool.system.Devices; import org.flashtool.util.BytesUtil; import org.flashtool.util.HexDump; import com.sun.jna.Native; import com.sun.jna.platform.win32.Kernel32; import com.sun.jna.platform.win32.Kernel32Util; import com.sun.jna.platform.win32.WinBase; import com.sun.jna.platform.win32.WinNT; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.win32.W32APIOptions; import lombok.extern.slf4j.Slf4j; @Slf4j public class JKernel32 { public static Kernel32RW kernel32 = (Kernel32RW) Native.loadLibrary("kernel32", Kernel32RW.class, W32APIOptions.UNICODE_OPTIONS); static WinNT.HANDLE HandleToDevice = WinBase.INVALID_HANDLE_VALUE; static WinBase.OVERLAPPED ovwrite = new WinBase.OVERLAPPED(); public static boolean openDevice() throws IOException { /* Kernel32RW.GENERIC_READ | Kernel32RW.GENERIC_WRITE not used in dwDesiredAccess field for system devices such a keyboard or mouse */ int shareMode = WinNT.FILE_SHARE_READ | WinNT.FILE_SHARE_WRITE; int Access = WinNT.GENERIC_WRITE | WinNT.GENERIC_READ; HandleToDevice = Kernel32.INSTANCE.CreateFile( Devices.getConnectedDeviceWin32().getDevPath(), Access, shareMode, null, WinNT.OPEN_EXISTING, 0,//WinNT.FILE_FLAG_OVERLAPPED, (WinNT.HANDLE)null); if (HandleToDevice == WinBase.INVALID_HANDLE_VALUE) throw new IOException(getLastError()); return true; } public static boolean openDeviceAsync() throws IOException { /* Kernel32RW.GENERIC_READ | Kernel32RW.GENERIC_WRITE not used in dwDesiredAccess field for system devices such a keyboard or mouse */ int shareMode = WinNT.FILE_SHARE_READ | WinNT.FILE_SHARE_WRITE; int Access = WinNT.GENERIC_WRITE | WinNT.GENERIC_READ; HandleToDevice = Kernel32.INSTANCE.CreateFile( Devices.getConnectedDeviceWin32().getDevPath(), Access, shareMode, null, WinNT.OPEN_EXISTING, WinNT.FILE_FLAG_OVERLAPPED, (WinNT.HANDLE)null); if (HandleToDevice == WinBase.INVALID_HANDLE_VALUE) throw new IOException(getLastError()); return true; } public static byte[] readBytes(int length) throws IOException { IntByReference nbread = new IntByReference(); byte[] b = new byte[length]; boolean result = kernel32.ReadFile(HandleToDevice, b, length, nbread, null); if (!result) throw new IOException("Read error :"+getLastError()); return BytesUtil.getReply(b,nbread.getValue()); } public static WinNT.HANDLE createEvent() throws IOException { WinNT.HANDLE hevent = kernel32.CreateEvent(null, false, false, null); int res = kernel32.GetLastError(); if (hevent == WinBase.INVALID_HANDLE_VALUE || res!=0) throw new IOException(JKernel32.getLastError()); return hevent; } public static void sleep(int ms) { try { Thread.sleep(ms); } catch (Exception e) {} } public static boolean writeBytes(byte bytes[]) throws IOException { IntByReference nbwritten = new IntByReference(); boolean result = kernel32.WriteFile(HandleToDevice, bytes, bytes.length, nbwritten, null); if (!result) throw new IOException(getLastError()); if (nbwritten.getValue()!=bytes.length) throw new IOException("Did not write all data"); bytes = null; return result; } public static boolean closeDevice() { boolean result = true; if (HandleToDevice != WinBase.INVALID_HANDLE_VALUE) { result = kernel32.CloseHandle(HandleToDevice); } HandleToDevice = WinBase.INVALID_HANDLE_VALUE; return result; } public static int getLastErrorCode() { return Kernel32.INSTANCE.GetLastError(); } public static String getLastError() { return Kernel32Util.getLastErrorMessage(); } }
4,010
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
Kernel32RW.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/win32/Kernel32RW.java
package org.flashtool.jna.win32; import com.sun.jna.platform.win32.Kernel32; import com.sun.jna.platform.win32.WinNT; import com.sun.jna.ptr.IntByReference; public interface Kernel32RW extends Kernel32 { /** * CreateFile constants */ /** * Enable read access */ int GENERIC_READ = 0x80000000; /** * Enable write access */ int GENERIC_WRITE = 0x40000000; /** * Read data from USB HID device. */ boolean ReadFile(WinNT.HANDLE Handle, byte[] buffer, int nNumberOfBytesToRead, IntByReference NumberOfBytesRead, OVERLAPPED Overlapped); /** * Write data to the USB HID device. */ boolean WriteFile(WinNT.HANDLE Handle, byte[] buffer, int NumberOfBytesToWrite, IntByReference NumberOfBytesWritten, OVERLAPPED Overlapped); boolean GetOverlappedResult(WinNT.HANDLE Handle,OVERLAPPED Overlapped,IntByReference NumberOfBytesRead, boolean wait); boolean CancelIo(WinNT.HANDLE Handle); //WinNT.HANDLE CreateEvent(Pointer securityAttributes, boolean manualReset, boolean initialState, String name); }
1,121
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
JsetupAPi.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/win32/JsetupAPi.java
package org.flashtool.jna.win32; import org.flashtool.jna.adb.AdbUtility; import org.flashtool.jna.linux.JUsb; import org.flashtool.jna.win32.SetupApi.HDEVINFO; import org.flashtool.jna.win32.SetupApi.SP_DEVICE_INTERFACE_DETAIL_DATA; import org.flashtool.jna.win32.SetupApi.SP_DRVINFO_DATA; import com.sun.jna.platform.win32.SetupApi.SP_DEVICE_INTERFACE_DATA; import com.sun.jna.platform.win32.SetupApi.SP_DEVINFO_DATA; import com.sun.jna.platform.win32.Guid.GUID; import com.sun.jna.ptr.IntByReference; import com.sun.jna.Native; import com.sun.jna.win32.W32APIOptions; import lombok.extern.slf4j.Slf4j; @Slf4j public class JsetupAPi { static SetupApi setupapi = (SetupApi) Native.loadLibrary("setupapi", SetupApi.class, W32APIOptions.UNICODE_OPTIONS); public static GUID USBGuid = new GUID(); private static SP_DEVINFO_DATA DeviceInfoData = new SP_DEVINFO_DATA(); private static SP_DRVINFO_DATA DriverInfoData = new SP_DRVINFO_DATA(); static { USBGuid.Data1=0xA5DCBF10; USBGuid.Data2=0x6530; USBGuid.Data3=0x11D2; USBGuid.Data4=new byte[8]; USBGuid.Data4[0]=(byte)0x90; USBGuid.Data4[1]=(byte)0x1F; USBGuid.Data4[2]=(byte)0x00; USBGuid.Data4[3]=(byte)0xC0; USBGuid.Data4[4]=(byte)0x4F; USBGuid.Data4[5]=(byte)0xB9; USBGuid.Data4[6]=(byte)0x51; USBGuid.Data4[7]=(byte)0xED; DeviceInfoData.cbSize = DeviceInfoData.size(); DriverInfoData.cbSize = DriverInfoData.size(); } public static String getClassName(GUID guid) { char[] ClassName = new char[100]; boolean result = setupapi.SetupDiClassNameFromGuid(guid, ClassName, 100, null); if (result) { String name = new String(); for (int i=0;i<100;i++) { if (ClassName[i]!=0) name = name+ClassName[i]; } return name; } else { log.error("Error calling SetupDiClassNameFromGuid"); } return ""; } public static GUID getGUID(String classname) { GUID[] ClassGuidList= new GUID[100]; IntByReference size = new IntByReference(); boolean result = setupapi.SetupDiClassGuidsFromName(classname, ClassGuidList, 100, size); if (result && (size.getValue()==1)) { return ClassGuidList[0]; } else { log.error("Error calling SetupDiClassNameFromGuid for "+classname); } return null; } public static void destroyHandle(HDEVINFO hDevInfo) { setupapi.SetupDiDestroyDeviceInfoList(hDevInfo); } public static SP_DEVINFO_DATA enumDevInfo(HDEVINFO hDevInfo, int index) { int result = setupapi.SetupDiEnumDeviceInfo(hDevInfo, index, DeviceInfoData); if (result == 0) { return null; } return DeviceInfoData; } public static boolean buildDriverList(HDEVINFO hDevInfo, SP_DEVINFO_DATA DeviceInfoData) { int buildresult = setupapi.SetupDiBuildDriverInfoList(hDevInfo, DeviceInfoData, SetupApi.SPDIT_COMPATDRIVER); if (buildresult == 0) { return false; } return true; } public static SP_DRVINFO_DATA enumDriverInfo(HDEVINFO hDevInfo, SP_DEVINFO_DATA DeviceInfoData, int index) { int result = setupapi.SetupDiEnumDriverInfo(hDevInfo, DeviceInfoData, SetupApi.SPDIT_COMPATDRIVER, index, DriverInfoData); if (result == 0) { return null; } return DriverInfoData; } public static SP_DRVINFO_DATA getDriver(HDEVINFO hDevInfo, SP_DEVINFO_DATA DeviceInfoData) { SP_DRVINFO_DATA DriverInfoData = new SP_DRVINFO_DATA(); DriverInfoData.cbSize=DriverInfoData.size(); int result = setupapi.SetupDiGetSelectedDriver(hDevInfo, DeviceInfoData, DriverInfoData); if (result == 0) { return null; } return DriverInfoData; } public static HDEVINFO getHandleForConnectedInterfaces() { return setupapi.SetupDiGetClassDevs(USBGuid, null, null, SetupApi.DIGCF_PRESENT|SetupApi.DIGCF_DEVICEINTERFACE); } public static HDEVINFO getHandleForConnectedDevices() { return setupapi.SetupDiGetClassDevs(null, null, null, SetupApi.DIGCF_PRESENT|SetupApi.DIGCF_ALLCLASSES); } public static boolean isInstalled(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData) { byte[] res = {'a','a','a','a'}; setupapi.SetupDiGetDeviceRegistryProperty(DeviceInfoSet, DeviceInfoData, SetupApi.SPDRP_INSTALL_STATE,null,res,4,null); return (res[0]==0); } public static String getDevId(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData) { char[] DeviceId = new char[100]; boolean result = setupapi.SetupDiGetDeviceInstanceId(DeviceInfoSet, DeviceInfoData, DeviceId, 100,null); if (result) { String name = new String(); for (int i=0;i<100;i++) { if (DeviceId[i]!=0) name = name+DeviceId[i]; } return name; } return ""; } public static String getDevicePath(HDEVINFO hDevInfo, SP_DEVINFO_DATA DeviceInfoData) { String devpath = ""; SP_DEVICE_INTERFACE_DATA DeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA(); DeviceInterfaceData.cbSize = DeviceInterfaceData.size(); /* Query the device using the index to get the interface data */ int index=0; do { int result = setupapi.SetupDiEnumDeviceInterfaces(hDevInfo, DeviceInfoData, USBGuid,index, DeviceInterfaceData); if (result == 0) { break; } /* A successful query was made, use it to get the detailed data of the device */ IntByReference reqlength = new IntByReference(); /* Obtain the length of the detailed data structure, and then allocate space and retrieve it */ result = setupapi.SetupDiGetDeviceInterfaceDetail(hDevInfo, DeviceInterfaceData, null, 0, reqlength, null); // Create SP_DEVICE_INTERFACE_DETAIL_DATA structure and set appropriate length for device Path */ SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA(reqlength.getValue()); result = setupapi.SetupDiGetDeviceInterfaceDetail(hDevInfo, DeviceInterfaceData, DeviceInterfaceDetailData, reqlength.getValue(), reqlength, null); devpath = Native.toString(DeviceInterfaceDetailData.devicePath); if (devpath.length()==0) { SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailDataDummy = new SP_DEVICE_INTERFACE_DETAIL_DATA(); DeviceInterfaceDetailData.cbSize=DeviceInterfaceDetailDataDummy.size(); result = setupapi.SetupDiGetDeviceInterfaceDetail(hDevInfo, DeviceInterfaceData, DeviceInterfaceDetailData, reqlength.getValue(), reqlength, null); devpath = Native.toString(DeviceInterfaceDetailData.devicePath); } index++; } while (true); return devpath; } }
6,555
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
SetupApi.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/win32/SetupApi.java
package org.flashtool.jna.win32; import java.util.Arrays; import java.util.List; import com.sun.jna.platform.win32.Guid.GUID; import com.sun.jna.Library; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.platform.win32.WinBase; import com.sun.jna.platform.win32.WinDef; import com.sun.jna.platform.win32.WinNT; import com.sun.jna.ptr.IntByReference; import com.sun.jna.platform.win32.SetupApi.SP_DEVINFO_DATA; import com.sun.jna.platform.win32.SetupApi.SP_DEVICE_INTERFACE_DATA; /** * Declare a Java interface that holds the native "setupapi.dll" library methods by extending the W32API interface. */ public interface SetupApi extends Library { public static class HDEVINFO extends WinNT.HANDLE {} public static class SP_DRVINFO_DATA extends Structure { public SP_DRVINFO_DATA() { DriverDate = new WinBase.FILETIME(); } public int cbSize; public int DriverType; public Pointer Reserved; public char[] Description = new char[255]; public char[] MfgName = new char[255]; public char[] ProviderName= new char[255]; public WinBase.FILETIME DriverDate; public long DriverVersion; protected List getFieldOrder() { return Arrays.asList("cbSize", "DriverType", "Reserved", "Description", "MfgName", "ProviderName", "DriverDate", "DriverVersion"); } } public static class SP_DEVICE_INTERFACE_DETAIL_DATA extends Structure { public static class ByReference extends SP_DEVINFO_DATA implements Structure.ByReference { public ByReference() { } public ByReference(Pointer memory) { super(memory); } } public SP_DEVICE_INTERFACE_DETAIL_DATA() { cbSize = size(); setAlignType(Structure.ALIGN_NONE); } public SP_DEVICE_INTERFACE_DETAIL_DATA(int size) { cbSize = size(); devicePath = new char[size]; setAlignType(Structure.ALIGN_NONE); } public SP_DEVICE_INTERFACE_DETAIL_DATA(Pointer memory) { super(memory); read(); } /** * The size, in bytes, of the SP_DEVINFO_DATA structure. */ public int cbSize; public char[] devicePath = new char[1]; protected List getFieldOrder() { return Arrays.asList("cbSize", "devicePath"); } } public static int DIGCF_DEFAULT = 0x00000001; public static int DIGCF_PRESENT = 0x00000002; public static int DIGCF_ALLCLASSES = 0x00000004; public static int DIGCF_PROFILE = 0x00000008; public static int DIGCF_DEVICEINTERFACE = 0x00000010; public static int SPDRP_DRIVER = 0x00000009; public static int SPDRP_INSTALL_STATE = 0x00000022; public static int SPDIT_COMPATDRIVER = 0x00000002; HDEVINFO SetupDiGetClassDevs(GUID Guid, String Enumerator, WinDef.HWND Parent, int Flags); int SetupDiBuildDriverInfoList(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, int DriverType); int SetupDiEnumDeviceInfo(HDEVINFO DeviceInfoSet, int MemberIndex, SP_DEVINFO_DATA DeviceInfoData); int SetupDiEnumDriverInfo(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, int DriverType, int MemberIndex, SP_DRVINFO_DATA DriverInfoData); int SetupDiEnumDeviceInterfaces(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, GUID Guid, int MemberIndex, SP_DEVICE_INTERFACE_DATA DeviceInterfaceData); int SetupDiGetDeviceInterfaceDetail(HDEVINFO DeviceInfoSet, SP_DEVICE_INTERFACE_DATA DeviceInterfaceData, SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData, int DeviceInterfaceDetailDataSize, IntByReference RequiredSize, SP_DEVINFO_DATA DeviceInfoData); int SetupDiDestroyDeviceInfoList(HDEVINFO DeviceInfoSet); boolean SetupDiGetDeviceInstanceId(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, char[] DeviceId, int DeviceInstanceIdSize,IntByReference RequiredSize); boolean SetupDiClassNameFromGuid(GUID Guid, char[] ClassName, int ClassNameSize, IntByReference RequiredSize); int SetupDiGetSelectedDriver(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, SP_DRVINFO_DATA DriverInfoData); boolean SetupDiClassGuidsFromName(String ClassName, GUID[] ClassGuidList, int ClassGuidListSize, IntByReference RequiredSize); boolean SetupDiGetDeviceRegistryProperty(HDEVINFO DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, int Property, IntByReference PropertyRegDataType, byte[] PropertyBuffer, int PropertyBufferSize, IntByReference RequiredSize); }
4,838
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
User32RW.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/win32/User32RW.java
package org.flashtool.jna.win32; import java.util.Arrays; import java.util.List; import org.flashtool.jna.linux.JUsb; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.platform.win32.User32; import com.sun.jna.platform.win32.WinNT.HANDLE; import com.sun.jna.win32.W32APIOptions; public interface User32RW extends User32 { public static final User32RW MYINSTANCE = (User32RW) Native.loadLibrary("user32", User32RW.class, W32APIOptions.UNICODE_OPTIONS); final int GWL_EXSTYLE = -20; final int GWL_STYLE = -16; final int GWL_WNDPROC = -4; final int GWL_HINSTANCE = -6; final int GWL_ID = -12; final int GWL_USERDATA = -21; final int DWL_DLGPROC = 4; final int DWL_MSGRESULT = 0; final int DWL_USER = 8; final int WS_EX_COMPOSITED = 0x20000000; final int WS_EX_LAYERED = 0x80000; final int WS_EX_TRANSPARENT = 32; final int WM_DESTROY = 0x0002; final int WM_CHANGECBCHAIN = 0x030D; final int WM_DRAWCLIPBOARD = 0x0308; int GetWindowLong(HWND hWnd, int nIndex); int SetWindowLong(HWND hWnd, int nIndex, int dwNewLong); interface WNDPROC extends StdCallCallback { int callback(HWND hWnd, int uMsg, WPARAM uParam, LPARAM lParam); } int SetWindowLong(HWND hWnd, int nIndex, WNDPROC proc); HWND CreateWindowEx(int styleEx, String className, String windowName, int style, int x, int y, int width, int height, HWND hndParent, int hndMenu, int hndInst, Object parm); final HWND HWND_TOPMOST = new HWND(Pointer.createConstant(-1)); final int SWP_NOSIZE = 1; boolean SetWindowPos(HWND hWnd, HWND hWndInsAfter, int x, int y, int cx, int cy, short uFlags); boolean DestroyWindow(HWND hwnd); HWND SetClipboardViewer(HWND hWndNewViewer); boolean ChangeClipboardChain(HWND hWndRemove, HWND hWndNewNext); // http://msdn.microsoft.com/en-us/library/ms644958(VS.85).aspx public static class POINT extends Structure { public int x; public int y; protected List getFieldOrder() { return Arrays.asList("x", "y"); } } /* * PeekMessage() Options */ final int PM_NOREMOVE = 0x0000; final int PM_REMOVE = 0x0001; final int PM_NOYIELD = 0x0002; class MSG extends Structure { public int hWnd; public int message; public short wParam; public int lParam; public int time; public POINT pt; protected List getFieldOrder() { return Arrays.asList("hWnd", "message", "wParam", "lParam", "time", "pt"); } } // http://msdn.microsoft.com/en-us/library/ms644936(VS.85).aspx int GetMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, int wMsgFilterMax); boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, int wMsgFilterMax, int wRemoveMsg); boolean TranslateMessage(MSG lpMsg); int DispatchMessage(MSG lpMsg); final int QS_KEY = 0x0001; final int QS_MOUSEMOVE = 0x0002; final int QS_MOUSEBUTTON = 0x0004; final int QS_POSTMESSAGE = 0x0008; final int QS_TIMER = 0x0010; final int QS_PAINT = 0x0020; final int QS_SENDMESSAGE = 0x0040; final int QS_HOTKEY = 0x0080; final int QS_ALLPOSTMESSAGE = 0x0100; final int QS_RAWINPUT = 0x0400; final int QS_MOUSE = (QS_MOUSEMOVE | QS_MOUSEBUTTON); final int QS_INPUT = (QS_MOUSE | QS_KEY | QS_RAWINPUT); final int QS_ALLEVENTS = (QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY); final int QS_ALLINPUT = (QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE); int MsgWaitForMultipleObjects(int nCount, HANDLE[] pHandles, boolean bWaitAll, int dwMilliseconds, int dwWakeMask); // void SendMessage(HWND hWnd, int message, WPARAM wParam, LPARAM lParam); void PostMessage(HWND hWnd, int message, WPARAM wParam, LPARAM lParam); LRESULT DefWindowProc(HWND hWnd, int msg, WPARAM wParam, LPARAM lParam); }
3,880
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
JUsb.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/linux/JUsb.java
package org.flashtool.jna.linux; import java.io.ByteArrayInputStream; import org.flashtool.jna.adb.APKUtility; import org.flashtool.libusb.LibUsbException; import org.flashtool.libusb.UsbDevList; import org.flashtool.libusb.UsbDevice; import org.flashtool.libusb.UsbSystem; import org.flashtool.util.BytesUtil; import lombok.extern.slf4j.Slf4j; @Slf4j public class JUsb { private static UsbSystem us=null; private static UsbDevice dev=null; private static String VendorId = ""; private static String DeviceId = ""; private static String Serial = ""; public static void init() throws LibUsbException { us = new UsbSystem(); } public static String getVersion() { if (us==null) return ""; return "libusb version " + us.getVersion(); } public static void fillDevice(boolean destroy) { dev = getDevice(); if (dev!=null) { VendorId = dev.getVendor().toUpperCase(); DeviceId = dev.getProduct().toUpperCase(); Serial = ""; if (destroy) { try { dev.open(); Serial = dev.getSerial(); dev.destroy(); } catch (Exception e) { VendorId = ""; DeviceId = ""; Serial = ""; try { dev.destroy(); } catch (Exception e1) {} } } } else { VendorId = ""; DeviceId = ""; Serial = ""; } } public static String getVendorId() { return VendorId; } public static String getProductId() { return DeviceId; } public static String getSerial() { return Serial; } public static UsbDevice getDevice() { UsbDevice device=null; try { UsbDevList ulist = us.getDevices("0fce"); if (ulist.size()> 0 ) { device = ulist.get(0); } } catch (LibUsbException e) {} return device; } public static void open() throws Exception { dev.openAndClaim(0); } public static void writeBytes(byte[] towrite) throws LibUsbException { dev.bulkWrite(BytesUtil.getReply(towrite, towrite.length)); } public static void close() { if (dev!=null) try { dev.releaseAndClose(); } catch (Exception e) {} } public static byte[] readBytes() throws LibUsbException { return dev.bulkRead(0x1000); } public static byte[] readBytes(int count) throws LibUsbException { return dev.bulkRead(count); } public static byte[] readBytes(int count, int timeout) throws LibUsbException { return dev.bulkRead(count); } public static void cleanup() throws Exception { us.endSystem(); } }
2,419
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
libusb_interface.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/libusb/libusb_interface.java
package org.flashtool.jna.libusb; import java.util.Arrays; import java.util.List; import org.flashtool.jna.adb.APKUtility; import com.sun.jna.Structure; import lombok.extern.slf4j.Slf4j; @Slf4j public class libusb_interface extends Structure { public libusb_interface_descriptor.ByReference altsetting; public int num_altsetting; public libusb_interface_descriptor.ByReference getAltsetting() { return this.altsetting; } public void setAltsetting(libusb_interface_descriptor.ByReference altsetting) { this.altsetting = altsetting; } public int getNum_altsetting() { return this.num_altsetting; } public void setNum_altsetting(int num_altsetting) { this.num_altsetting = num_altsetting; } public libusb_interface() { } protected List getFieldOrder() { return Arrays.asList("altsetting", "num_altsetting"); } public libusb_interface(libusb_interface_descriptor.ByReference altsetting, int num_altsetting) { this.altsetting = altsetting; this.num_altsetting = num_altsetting; } public static class ByReference extends libusb_interface implements Structure.ByReference { } public static class ByValue extends libusb_interface implements Structure.ByValue { } }
1,254
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
LibUsbLibrary.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/libusb/LibUsbLibrary.java
package org.flashtool.jna.libusb; import org.flashtool.jna.adb.APKUtility; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.PointerByReference; public abstract interface LibUsbLibrary extends Library { public static final LibUsbLibrary libUsb = (LibUsbLibrary)Native.loadLibrary("usbx-1.0", LibUsbLibrary.class); public static final int LIBUSB_ISO_SYNC_TYPE_MASK = 12; public static final int LIBUSB_ISO_USAGE_TYPE_MASK = 48; public static final int LIBUSBX_API_VERSION = 16777471; public static final int LIBUSB_DT_DEVICE_SIZE = 18; public static final int LIBUSB_ENDPOINT_ADDRESS_MASK = 15; public static final int LIBUSB_DT_CONFIG_SIZE = 9; public static final int LIBUSB_TRANSFER_TYPE_MASK = 3; public static final int LIBUSB_ENDPOINT_DIR_MASK = 128; public static final int LIBUSB_DT_ENDPOINT_AUDIO_SIZE = 9; public static final int LIBUSB_DT_ENDPOINT_SIZE = 7; public static final int LIBUSB_DT_HUB_NONVAR_SIZE = 7; public static final int LIBUSB_DT_INTERFACE_SIZE = 9; public abstract int libusb_init(Pointer[] paramArrayOfPointer); public abstract void libusb_exit(Pointer paramPointer); public abstract int libusb_get_device_list(Pointer paramPointer, Pointer[] paramArrayOfPointer); public abstract void libusb_free_device_list(Pointer paramPointer, int paramInt); public abstract Pointer libusb_get_device(Pointer paramPointer); public abstract int libusb_get_device_descriptor(Pointer paramPointer, libusb_device_descriptor[] paramArrayOflibusb_device_descriptor); public abstract int libusb_get_string_descriptor_ascii(Pointer paramPointer, byte paramByte, byte[] paramArrayOfByte, int paramInt); public abstract int libusb_open(Pointer paramPointer, Pointer[] paramArrayOfPointer); public abstract void libusb_close(Pointer paramPointer); public abstract int libusb_get_config_descriptor(Pointer paramPointer, int paramInt, PointerByReference paramPointerByReference); public abstract void libusb_free_config_descriptor(Pointer paramPointer); public abstract void libusb_ref_device(Pointer paramPointer); public abstract void libusb_unref_device(Pointer paramPointer); public abstract int libusb_detach_kernel_driver(Pointer paramPointer, int paramInt); public abstract int libusb_attach_kernel_driver(Pointer paramPointer, int paramInt); public abstract int libusb_claim_interface(Pointer paramPointer, int paramInt); public abstract int libusb_release_interface(Pointer paramPointer, int paramInt); public abstract int libusb_bulk_transfer(Pointer paramPointer, byte paramByte, byte[] paramArrayOfByte, int paramInt1, int[] paramArrayOfInt, int paramInt2); public abstract void libusb_set_debug(Pointer paramPointer, int paramInt); public abstract libusb_version libusb_get_version(); public static abstract interface libusb_class_code { public static final int LIBUSB_CLASS_PER_INTERFACE = 0; public static final int LIBUSB_CLASS_AUDIO = 1; public static final int LIBUSB_CLASS_COMM = 2; public static final int LIBUSB_CLASS_HID = 3; public static final int LIBUSB_CLASS_PHYSICAL = 5; public static final int LIBUSB_CLASS_PRINTER = 7; public static final int LIBUSB_CLASS_PTP = 6; public static final int LIBUSB_CLASS_IMAGE = 6; public static final int LIBUSB_CLASS_MASS_STORAGE = 8; public static final int LIBUSB_CLASS_HUB = 9; public static final int LIBUSB_CLASS_DATA = 10; public static final int LIBUSB_CLASS_SMART_CARD = 11; public static final int LIBUSB_CLASS_CONTENT_SECURITY = 13; public static final int LIBUSB_CLASS_VIDEO = 14; public static final int LIBUSB_CLASS_PERSONAL_HEALTHCARE = 15; public static final int LIBUSB_CLASS_DIAGNOSTIC_DEVICE = 220; public static final int LIBUSB_CLASS_WIRELESS = 224; public static final int LIBUSB_CLASS_APPLICATION = 254; public static final int LIBUSB_CLASS_VENDOR_SPEC = 255; } public static abstract interface libusb_descriptor_type { public static final int LIBUSB_DT_DEVICE = 1; public static final int LIBUSB_DT_CONFIG = 2; public static final int LIBUSB_DT_STRING = 3; public static final int LIBUSB_DT_INTERFACE = 4; public static final int LIBUSB_DT_ENDPOINT = 5; public static final int LIBUSB_DT_HID = 33; public static final int LIBUSB_DT_REPORT = 34; public static final int LIBUSB_DT_PHYSICAL = 35; public static final int LIBUSB_DT_HUB = 41; public static final int LIBUSB_DT_SUPERSPEED_HUB = 42; } public static abstract interface libusb_endpoint_direction { public static final int LIBUSB_ENDPOINT_IN = 128; public static final int LIBUSB_ENDPOINT_OUT = 0; } public static abstract interface libusb_error { public static final int LIBUSB_SUCCESS = 0; public static final int LIBUSB_ERROR_IO = -1; public static final int LIBUSB_ERROR_INVALID_PARAM = -2; public static final int LIBUSB_ERROR_ACCESS = -3; public static final int LIBUSB_ERROR_NO_DEVICE = -4; public static final int LIBUSB_ERROR_NOT_FOUND = -5; public static final int LIBUSB_ERROR_BUSY = -6; public static final int LIBUSB_ERROR_TIMEOUT = -7; public static final int LIBUSB_ERROR_OVERFLOW = -8; public static final int LIBUSB_ERROR_PIPE = -9; public static final int LIBUSB_ERROR_INTERRUPTED = -10; public static final int LIBUSB_ERROR_NO_MEM = -11; public static final int LIBUSB_ERROR_NOT_SUPPORTED = -12; public static final int LIBUSB_ERROR_OTHER = -99; } public static abstract interface libusb_iso_sync_type { public static final int LIBUSB_ISO_SYNC_TYPE_NONE = 0; public static final int LIBUSB_ISO_SYNC_TYPE_ASYNC = 1; public static final int LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 2; public static final int LIBUSB_ISO_SYNC_TYPE_SYNC = 3; } public static abstract interface libusb_iso_usage_type { public static final int LIBUSB_ISO_USAGE_TYPE_DATA = 0; public static final int LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 1; public static final int LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 2; } public static abstract interface libusb_log_level { public static final int LIBUSB_LOG_LEVEL_NONE = 0; public static final int LIBUSB_LOG_LEVEL_ERROR = 1; public static final int LIBUSB_LOG_LEVEL_WARNING = 2; public static final int LIBUSB_LOG_LEVEL_INFO = 3; public static final int LIBUSB_LOG_LEVEL_DEBUG = 4; } public static abstract interface libusb_request_recipient { public static final int LIBUSB_RECIPIENT_DEVICE = 0; public static final int LIBUSB_RECIPIENT_INTERFACE = 1; public static final int LIBUSB_RECIPIENT_ENDPOINT = 2; public static final int LIBUSB_RECIPIENT_OTHER = 3; } public static abstract interface libusb_request_type { public static final int LIBUSB_REQUEST_TYPE_STANDARD = 0; public static final int LIBUSB_REQUEST_TYPE_CLASS = 32; public static final int LIBUSB_REQUEST_TYPE_VENDOR = 64; public static final int LIBUSB_REQUEST_TYPE_RESERVED = 96; } public static abstract interface libusb_speed { public static final int LIBUSB_SPEED_UNKNOWN = 0; public static final int LIBUSB_SPEED_LOW = 1; public static final int LIBUSB_SPEED_FULL = 2; public static final int LIBUSB_SPEED_HIGH = 3; public static final int LIBUSB_SPEED_SUPER = 4; } public static abstract interface libusb_standard_request { public static final int LIBUSB_REQUEST_GET_STATUS = 0; public static final int LIBUSB_REQUEST_CLEAR_FEATURE = 1; public static final int LIBUSB_REQUEST_SET_FEATURE = 3; public static final int LIBUSB_REQUEST_SET_ADDRESS = 5; public static final int LIBUSB_REQUEST_GET_DESCRIPTOR = 6; public static final int LIBUSB_REQUEST_SET_DESCRIPTOR = 7; public static final int LIBUSB_REQUEST_GET_CONFIGURATION = 8; public static final int LIBUSB_REQUEST_SET_CONFIGURATION = 9; public static final int LIBUSB_REQUEST_GET_INTERFACE = 10; public static final int LIBUSB_REQUEST_SET_INTERFACE = 11; public static final int LIBUSB_REQUEST_SYNCH_FRAME = 12; public static final int LIBUSB_REQUEST_SET_SEL = 48; public static final int LIBUSB_SET_ISOCH_DELAY = 49; } public static abstract interface libusb_transfer_flags { public static final int LIBUSB_TRANSFER_SHORT_NOT_OK = 1; public static final int LIBUSB_TRANSFER_FREE_BUFFER = 2; public static final int LIBUSB_TRANSFER_FREE_TRANSFER = 4; public static final int LIBUSB_TRANSFER_ADD_ZERO_PACKET = 8; } public static abstract interface libusb_transfer_status { public static final int LIBUSB_TRANSFER_COMPLETED = 0; public static final int LIBUSB_TRANSFER_ERROR = 1; public static final int LIBUSB_TRANSFER_TIMED_OUT = 2; public static final int LIBUSB_TRANSFER_CANCELLED = 3; public static final int LIBUSB_TRANSFER_STALL = 4; public static final int LIBUSB_TRANSFER_NO_DEVICE = 5; public static final int LIBUSB_TRANSFER_OVERFLOW = 6; } public static abstract interface libusb_transfer_type { public static final int LIBUSB_TRANSFER_TYPE_CONTROL = 0; public static final int LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1; public static final int LIBUSB_TRANSFER_TYPE_BULK = 2; public static final int LIBUSB_TRANSFER_TYPE_INTERRUPT = 3; } }
9,369
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
libusb_config_descriptor.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/libusb/libusb_config_descriptor.java
package org.flashtool.jna.libusb; import java.util.Arrays; import java.util.List; import org.flashtool.jna.adb.APKUtility; import com.sun.jna.Pointer; import com.sun.jna.Structure; import lombok.extern.slf4j.Slf4j; @Slf4j public class libusb_config_descriptor extends Structure { public byte bLength; public byte bDescriptorType; public short wTotalLength; public byte bNumInterfaces; public byte bConfigurationValue; public byte iConfiguration; public byte bmAttributes; public byte MaxPower; public libusb_interface.ByReference iFaces; public Pointer extra; public int extra_length; protected List getFieldOrder() { return Arrays.asList("bLength", "bDescriptorType", "wTotalLength", "bNumInterfaces", "bConfigurationValue", "iConfiguration", "bmAttributes", "MaxPower", "iFaces", "extra", "extra_length"); } public libusb_config_descriptor() {} public libusb_config_descriptor[] toArray(int size) { return (libusb_config_descriptor[])super.toArray(size); } public libusb_config_descriptor(Pointer p) { super(p); read(); } public static class ByReference extends libusb_config_descriptor implements Structure.ByReference { } public static class ByValue extends libusb_config_descriptor implements Structure.ByValue { } }
1,433
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
libusb_interface_descriptor.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/libusb/libusb_interface_descriptor.java
package org.flashtool.jna.libusb; import java.util.Arrays; import java.util.List; import org.flashtool.jna.adb.APKUtility; import com.sun.jna.Pointer; import com.sun.jna.Structure; import lombok.extern.slf4j.Slf4j; @Slf4j public class libusb_interface_descriptor extends Structure { public byte bLength; public byte bDescriptorType; public byte bInterfaceNumber; public byte bAlternateSetting; public byte bNumEndpoints; public byte bInterfaceClass; public byte bInterfaceSubClass; public byte bInterfaceProtocol; public byte iInterface; public libusb_endpoint_descriptor.ByReference endpoint; public Pointer extra; public int extra_length; public byte getBLength() { return this.bLength; } public void setBLength(byte bLength) { this.bLength = bLength; } public byte getBDescriptorType() { return this.bDescriptorType; } public void setBDescriptorType(byte bDescriptorType) { this.bDescriptorType = bDescriptorType; } public byte getBInterfaceNumber() { return this.bInterfaceNumber; } public void setBInterfaceNumber(byte bInterfaceNumber) { this.bInterfaceNumber = bInterfaceNumber; } public byte getBAlternateSetting() { return this.bAlternateSetting; } public void setBAlternateSetting(byte bAlternateSetting) { this.bAlternateSetting = bAlternateSetting; } public byte getBNumEndpoints() { return this.bNumEndpoints; } public void setBNumEndpoints(byte bNumEndpoints) { this.bNumEndpoints = bNumEndpoints; } public byte getBInterfaceClass() { return this.bInterfaceClass; } public void setBInterfaceClass(byte bInterfaceClass) { this.bInterfaceClass = bInterfaceClass; } public byte getBInterfaceSubClass() { return this.bInterfaceSubClass; } public void setBInterfaceSubClass(byte bInterfaceSubClass) { this.bInterfaceSubClass = bInterfaceSubClass; } public byte getBInterfaceProtocol() { return this.bInterfaceProtocol; } public void setBInterfaceProtocol(byte bInterfaceProtocol) { this.bInterfaceProtocol = bInterfaceProtocol; } public byte getIInterface() { return this.iInterface; } public void setIInterface(byte iInterface) { this.iInterface = iInterface; } public libusb_endpoint_descriptor.ByReference getEndpoint() { return this.endpoint; } public void setEndpoint(libusb_endpoint_descriptor.ByReference endpoint) { this.endpoint = endpoint; } public Pointer getExtra() { return this.extra; } public void setExtra(Pointer extra) { this.extra = extra; } public int getExtra_length() { return this.extra_length; } public void setExtra_length(int extra_length) { this.extra_length = extra_length; } public libusb_interface_descriptor() { } protected List getFieldOrder() { return Arrays.asList("bLength", "bDescriptorType", "bInterfaceNumber", "bAlternateSetting", "bNumEndpoints", "bInterfaceClass", "bInterfaceSubClass", "bInterfaceProtocol", "iInterface", "endpoint", "extra", "extra_length"); } public static class ByReference extends libusb_interface_descriptor implements Structure.ByReference { } public static class ByValue extends libusb_interface_descriptor implements Structure.ByValue { } }
3,311
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
libusb_device_descriptor.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/libusb/libusb_device_descriptor.java
package org.flashtool.jna.libusb; import java.util.Arrays; import java.util.List; import org.flashtool.jna.adb.APKUtility; import com.sun.jna.Structure; import lombok.extern.slf4j.Slf4j; @Slf4j public class libusb_device_descriptor extends Structure { public byte bLength; public byte bDescriptorType; public short bcdUSB; public byte bDeviceClass; public byte bDeviceSubClass; public byte bDeviceProtocol; public byte bMaxPacketSize0; public short idVendor; public short idProduct; public short bcdDevice; public byte iManufacturer; public byte iProduct; public byte iSerialNumber; public byte bNumConfigurations; public libusb_device_descriptor() {} protected List getFieldOrder() { return Arrays.asList("bLength", "bDescriptorType", "bcdUSB", "bDeviceClass", "bDeviceSubClass", "bDeviceProtocol", "bMaxPacketSize0", "idVendor", "idProduct", "bcdDevice", "iManufacturer", "iProduct", "iSerialNumber", "bNumConfigurations"); } public String toString() { return "libusb_device_descriptor { bLength=" + this.bLength + " bDescriptorType=" + this.bDescriptorType + " bcdUSB=" + this.bcdUSB + " bDeviceClass=" + this.bDeviceClass + " bDeviceSubClass=" + this.bDeviceSubClass + " bDeviceProtocol=" + this.bDeviceProtocol + " bMaxPacketSize0=" + this.bMaxPacketSize0 + " idVendor=" + this.idVendor + " idProduct=" + this.idProduct + " bcdDevice=" + this.bcdDevice + " iManufacturer=" + this.iManufacturer + " iProduct=" + this.iProduct + " iSerialNumber=" + this.iSerialNumber + " bNumConfigurations=" + this.bNumConfigurations + "}"; } public static class ByReference extends libusb_device_descriptor implements Structure.ByReference { } public static class ByValue extends libusb_device_descriptor implements Structure.ByValue { } }
1,913
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
libusb_endpoint_descriptor.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/libusb/libusb_endpoint_descriptor.java
package org.flashtool.jna.libusb; import java.util.Arrays; import java.util.List; import org.flashtool.jna.adb.APKUtility; import com.sun.jna.Pointer; import com.sun.jna.Structure; import lombok.extern.slf4j.Slf4j; @Slf4j public class libusb_endpoint_descriptor extends Structure { public byte bLength; public byte bDescriptorType; public byte bEndpointAddress; public byte bmAttributes; public short wMaxPacketSize; public byte bInterval; public byte bRefresh; public byte bSynchAddress; public Pointer extra; public int extra_length; public byte getBLength() { return this.bLength; } public void setBLength(byte bLength) { this.bLength = bLength; } public byte getBDescriptorType() { return this.bDescriptorType; } public void setBDescriptorType(byte bDescriptorType) { this.bDescriptorType = bDescriptorType; } public byte getBEndpointAddress() { return this.bEndpointAddress; } public void setBEndpointAddress(byte bEndpointAddress) { this.bEndpointAddress = bEndpointAddress; } public byte getBmAttributes() { return this.bmAttributes; } public void setBmAttributes(byte bmAttributes) { this.bmAttributes = bmAttributes; } public short getWMaxPacketSize() { return this.wMaxPacketSize; } public void setWMaxPacketSize(short wMaxPacketSize) { this.wMaxPacketSize = wMaxPacketSize; } public byte getBInterval() { return this.bInterval; } public void setBInterval(byte bInterval) { this.bInterval = bInterval; } public byte getBRefresh() { return this.bRefresh; } public void setBRefresh(byte bRefresh) { this.bRefresh = bRefresh; } public byte getBSynchAddress() { return this.bSynchAddress; } public void setBSynchAddress(byte bSynchAddress) { this.bSynchAddress = bSynchAddress; } public Pointer getExtra() { return this.extra; } public void setExtra(Pointer extra) { this.extra = extra; } public int getExtra_length() { return this.extra_length; } public void setExtra_length(int extra_length) { this.extra_length = extra_length; } public libusb_endpoint_descriptor() { } protected List getFieldOrder() { return Arrays.asList("bLength", "bDescriptorType", "bEndpointAddress", "bmAttributes", "wMaxPacketSize", "bInterval", "bRefresh", "bSynchAddress", "extra", "extra_length"); } public static class ByReference extends libusb_endpoint_descriptor implements Structure.ByReference { } public static class ByValue extends libusb_endpoint_descriptor implements Structure.ByValue { } }
2,638
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z
libusb_version.java
/FileExtraction/Java_unseen/Androxyde_Flashtool/Flashtool/src/main/java/org/flashtool/jna/libusb/libusb_version.java
package org.flashtool.jna.libusb; import java.util.Arrays; import java.util.List; import org.flashtool.jna.adb.APKUtility; import com.sun.jna.Pointer; import com.sun.jna.Structure; import lombok.extern.slf4j.Slf4j; @Slf4j public class libusb_version extends Structure { public short major; public short minor; public short micro; public short nano; public Pointer rc; public Pointer describe; public short getMajor() { return this.major; } public void setMajor(short major) { this.major = major; } public short getMinor() { return this.minor; } public void setMinor(short minor) { this.minor = minor; } public short getMicro() { return this.micro; } public void setMicro(short micro) { this.micro = micro; } public short getNano() { return this.nano; } public void setNano(short nano) { this.nano = nano; } public Pointer getRc() { return this.rc; } public void setRc(Pointer rc) { this.rc = rc; } public Pointer getDescribe() { return this.describe; } public void setDescribe(Pointer describe) { this.describe = describe; } public libusb_version() { } protected List getFieldOrder() { return Arrays.asList("major", "minor", "micro", "nano", "rc", "describe"); } public libusb_version(short major, short minor, short micro, short nano, Pointer rc, Pointer describe) { this.major = major; this.minor = minor; this.micro = micro; this.nano = nano; this.rc = rc; this.describe = describe; } public static class ByReference extends libusb_version implements Structure.ByReference { } public static class ByValue extends libusb_version implements Structure.ByValue { } }
1,763
Java
.java
Androxyde/Flashtool
468
244
165
2014-04-17T19:54:33Z
2024-03-12T15:17:26Z