├── README.md └── samples ├── R ├── README.md └── UTS REST API - R starting kit - version 0.1.html ├── java ├── pom.xml ├── resources │ ├── findings.txt │ └── hpo-codes.txt └── src │ └── test │ └── java │ └── uts │ └── rest │ └── samples │ ├── classes │ ├── AtomLite.java │ ├── ConceptLite.java │ ├── SearchResult.java │ └── SourceAtomClusterLite.java │ ├── content │ ├── RetrieveAtomsTestCase.java │ ├── RetrieveCodeTestCase.java │ ├── RetrieveCuiTestCase.java │ └── WalkHierarchyTestCase.java │ ├── cookbook │ └── CodeCrosswalk.java │ ├── search │ ├── BatchTermToCuiOrCodeTestCase.java │ └── SearchTermsTestCase.java │ └── util │ └── RestTicketClient.java ├── perl ├── crosswalk.pl ├── lib │ └── Authentication │ │ └── TicketClient.pm ├── retrieve-atoms.pl ├── retrieve-cui-or-code.pl ├── search-terms.pl └── walk-hierarchy.pl └── python ├── Authentication.py ├── crosswalk.py ├── get-content-view-members.py ├── get-rxcui-ingredients.py ├── get-rxcui-status.py ├── get-rxcuis-by-tty.py ├── hpo-codes.txt ├── retrieve-cui-or-code.py ├── retrieve-usp-atoms-from-umls.py ├── retrieve-value-set-info.py ├── search-terms.py └── walk-hierarchy.py /README.md: -------------------------------------------------------------------------------- 1 | 2 | # uts-rest-api (archived) 3 | 4 | This repository is no longer maintained. The scripts in this repository may no longer work as expected. For additional help with scripting against the UMLS API, see the following resources: 5 | 6 | [Python script examples](https://documentation.uts.nlm.nih.gov/rest/rest-api-cookbook/python-scripts.html) - A few sample python scripts that can help you to perform basic batch requests against the UMLS API. 7 | 8 | [Postman examples](https://documentation.uts.nlm.nih.gov/rest/rest-api-cookbook/postman.html) - API request examples that can be loaded in the Postman application. 9 | 10 | [UMLS Community](https://www.nlm.nih.gov/research/umls/implementation_resources/community/index.html) - A collection of user-contributed applications and scripts that extend the functionality of the UMLS. 11 | -------------------------------------------------------------------------------- /samples/R/README.md: -------------------------------------------------------------------------------- 1 | #R examples 2 | -------------------------------------------------------------------------------- /samples/java/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | gov.nih.nlm.uts.api.rest.samples 4 | uts-rest-api-samples 5 | 0.0.1-SNAPSHOT 6 | UTS REST API Samples 7 | 8 | 9 | central 10 | Maven Central Repository 11 | https://repo1.maven.org/maven2 12 | 13 | 14 | 15 | 16 | commons-lang 17 | commons-lang 18 | 2.6 19 | 20 | 21 | junit 22 | junit 23 | 4.12 24 | 25 | 26 | com.jayway.restassured 27 | rest-assured 28 | 2.4.0 29 | 30 | 31 | com.jayway.jsonpath 32 | json-path 33 | 2.0.0 34 | 35 | 36 | com.jayway.restassured 37 | xml-path 38 | 2.4.0 39 | 40 | 41 | com.fasterxml.jackson.core 42 | jackson-core 43 | 2.9.7 44 | 45 | 46 | com.fasterxml.jackson.core 47 | jackson-annotations 48 | 2.9.7 49 | 50 | 51 | com.fasterxml.jackson.core 52 | jackson-databind 53 | 2.10.0.pr1 54 | 55 | 56 | com.codesnippets4all 57 | quick-json 58 | 1.0.4 59 | 60 | 61 | log4j 62 | log4j 63 | 1.2.17 64 | 65 | 66 | -------------------------------------------------------------------------------- /samples/java/resources/findings.txt: -------------------------------------------------------------------------------- 1 | diabetic foot 2 | kidney stones 3 | plantar fasciitis 4 | subarachnoid hemorrhage 5 | metatarsal fracture 6 | bloom syndrome 7 | Glycogen storage disease 8 | Leigh Syndrome 9 | idiopathic neuropathy 10 | nephritis 11 | systemic lupus erythematosus 12 | neonatal hypoglycemia -------------------------------------------------------------------------------- /samples/java/resources/hpo-codes.txt: -------------------------------------------------------------------------------- 1 | HP:0001735 2 | HP:0001947 3 | HP:0100631 4 | HP:0001022 5 | HP:0001596 6 | HP:0000646 7 | HP:0009916 8 | HP:0100845 9 | HP:0001102 10 | HP:0000739 11 | HP:0000787 12 | HP:0011484 13 | HP:0001871 14 | HP:0030346 -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/classes/AtomLite.java: -------------------------------------------------------------------------------- 1 | package uts.rest.samples.classes; 2 | import com.fasterxml.jackson.annotation.*; 3 | 4 | //ignorable properties are of customizable - this is just an example 5 | @JsonIgnoreProperties({"classType","attributes","definitions","relations","contentViewMemberships"}) 6 | 7 | public class AtomLite { 8 | 9 | private String ui; 10 | private String name; 11 | private String termType; 12 | private String language; 13 | private boolean suppressible; 14 | private boolean obsolete; 15 | private String rootSource; 16 | private String concept; 17 | private String code; 18 | private String sourceConcept; 19 | private String sourceDescriptor; 20 | private String parents; 21 | private String children; 22 | private String ancestors; 23 | private String descendants; 24 | 25 | 26 | public String getUi() { 27 | 28 | return this.ui; 29 | } 30 | 31 | public String getName() { 32 | 33 | return this.name; 34 | } 35 | 36 | public String getTermType() { 37 | 38 | return this.termType; 39 | } 40 | 41 | public String getLanguage() { 42 | 43 | return this.language; 44 | } 45 | 46 | public String getConcept() { 47 | 48 | return this.concept; 49 | } 50 | 51 | public String getSourceConcept() { 52 | 53 | return this.sourceConcept; 54 | } 55 | 56 | public String getSourceDescriptor() { 57 | 58 | return this.sourceDescriptor; 59 | } 60 | 61 | 62 | public String getCode() { 63 | 64 | return this.code; 65 | } 66 | 67 | public boolean getObsolete() { 68 | 69 | return this.obsolete; 70 | } 71 | 72 | public boolean getSupressible() { 73 | 74 | return this.suppressible; 75 | } 76 | 77 | public String getRootSource() { 78 | 79 | return this.rootSource; 80 | } 81 | 82 | public String getParents() { 83 | 84 | return this.parents; 85 | } 86 | 87 | public String getChildren() { 88 | 89 | return this.children; 90 | } 91 | 92 | public String getAncestors() { 93 | 94 | return this.ancestors; 95 | } 96 | 97 | public String getDescendants() { 98 | 99 | return this.descendants; 100 | } 101 | 102 | private void setUi(String ui) { 103 | 104 | this.ui = ui; 105 | } 106 | 107 | private void setTermType(String termType){ 108 | 109 | this.termType = termType; 110 | } 111 | 112 | private void setName(String name) { 113 | 114 | this.name = name; 115 | } 116 | 117 | private void setLanguage (String language) { 118 | 119 | this.language = language; 120 | } 121 | 122 | 123 | private void setObsolete (boolean obsolete) { 124 | 125 | this.obsolete = obsolete; 126 | } 127 | 128 | private void setRootSource(String rootSource) { 129 | 130 | this.rootSource = rootSource; 131 | } 132 | 133 | private void setSuppressible (boolean suppressible) { 134 | 135 | this.suppressible = suppressible; 136 | } 137 | 138 | private void setParents (String parents) { 139 | 140 | this.parents = parents; 141 | } 142 | 143 | private void setChildren (String children) { 144 | 145 | this.children = children; 146 | } 147 | 148 | public void setAncestors (String ancestors) { 149 | 150 | this.ancestors = ancestors; 151 | } 152 | 153 | public void setDescendants (String descendants) { 154 | 155 | this.descendants = descendants; 156 | } 157 | 158 | } 159 | -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/classes/ConceptLite.java: -------------------------------------------------------------------------------- 1 | package uts.rest.samples.classes; 2 | import java.util.HashMap; 3 | import java.util.List; 4 | 5 | import com.fasterxml.jackson.annotation.*; 6 | 7 | //of course these are customizable 8 | @JsonIgnoreProperties({"classType","dateAdded","majorRevisionDate","status","attributeCount","cvMemberCount","suppressible","relationCount"}) 9 | 10 | public class ConceptLite { 11 | 12 | private String ui; 13 | private String name; 14 | private List> semanticTypes; 15 | private int atomCount; 16 | private String atoms; 17 | private String relations; 18 | private String definitions; 19 | private String defaultPreferredAtom; 20 | 21 | public String getUi() { 22 | 23 | return this.ui; 24 | } 25 | 26 | public String getName() { 27 | 28 | return this.name; 29 | } 30 | 31 | public List> getSemanticTypes() { 32 | 33 | return this.semanticTypes; 34 | } 35 | 36 | public String getAtoms() { 37 | 38 | return this.atoms; 39 | } 40 | 41 | public int getAtomCount() { 42 | 43 | return this.atomCount; 44 | } 45 | 46 | public String getDefinitions() { 47 | 48 | return this.definitions; 49 | } 50 | 51 | public String getRelations() { 52 | 53 | return this.relations; 54 | } 55 | 56 | public String getDefaultPreferredAtom() { 57 | 58 | return this.defaultPreferredAtom; 59 | } 60 | 61 | private void setAtoms(String atoms) { 62 | 63 | this.atoms = atoms; 64 | } 65 | 66 | private void setUi(String ui) { 67 | 68 | this.ui = ui; 69 | } 70 | 71 | private void setName(String name){ 72 | 73 | this.name=name; 74 | } 75 | 76 | public void setSemanticTypes(List> stys) { 77 | 78 | this.semanticTypes = stys; 79 | } 80 | 81 | private void setDefinitions (String definitions) { 82 | 83 | this.definitions = definitions; 84 | } 85 | 86 | private void setRelations (String relations) { 87 | 88 | this.relations = relations; 89 | } 90 | 91 | private void setDefaultPreferredAtom(String defaultPreferredAtom) { 92 | 93 | this.defaultPreferredAtom = defaultPreferredAtom; 94 | 95 | } 96 | } -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/classes/SearchResult.java: -------------------------------------------------------------------------------- 1 | package uts.rest.samples.classes; 2 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 3 | 4 | 5 | public class SearchResult { 6 | 7 | private String ui; 8 | private String name; 9 | private String uri; 10 | private String rootSource; 11 | 12 | //getters 13 | public String getUi() { 14 | 15 | return this.ui; 16 | } 17 | 18 | public String getName() { 19 | 20 | return this.name; 21 | } 22 | 23 | public String getUri() { 24 | 25 | return this.uri; 26 | } 27 | 28 | public String getRootSource() { 29 | 30 | return this.rootSource; 31 | } 32 | 33 | //setters 34 | private void setUi(String ui) { 35 | 36 | this.ui = ui; 37 | } 38 | 39 | private void setName(String name) { 40 | 41 | this.name = name; 42 | } 43 | 44 | private void setUri(String uri) { 45 | 46 | this.uri = uri; 47 | } 48 | 49 | private void setRootSource(String rootSource) { 50 | 51 | this.rootSource = rootSource; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/classes/SourceAtomClusterLite.java: -------------------------------------------------------------------------------- 1 | package uts.rest.samples.classes; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | 6 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 7 | 8 | @JsonIgnoreProperties({"classType"}) 9 | 10 | public class SourceAtomClusterLite { 11 | 12 | 13 | private String ui; 14 | private String name; 15 | private boolean obsolete; 16 | private boolean suppressible; 17 | private String rootSource; 18 | private int cVMemberCount; 19 | private int atomCount; 20 | private String concepts; 21 | private String atoms; 22 | private String parents; 23 | private String children; 24 | private String descendants; 25 | private String ancestors; 26 | private String relations; 27 | private String definitions; 28 | private String attributes; 29 | private String defaultPreferredAtom; 30 | private List> subsetMemberships; 31 | private List> contentViewMemberships; 32 | 33 | 34 | public String getUi() { 35 | 36 | return this.ui; 37 | } 38 | 39 | public String getName() { 40 | 41 | return this.name; 42 | } 43 | 44 | public boolean getObsolete() { 45 | 46 | return this.obsolete; 47 | } 48 | 49 | public boolean getSuppressible() { 50 | 51 | return this.suppressible; 52 | } 53 | 54 | public String getAtoms() { 55 | 56 | return this.atoms; 57 | } 58 | 59 | public String getConcepts() { 60 | 61 | return this.concepts; 62 | } 63 | 64 | public String getRootSource() { 65 | 66 | return this.rootSource; 67 | } 68 | 69 | public int getAtomCount() { 70 | 71 | return this.atomCount; 72 | } 73 | 74 | public int getCVMemberCount() { 75 | 76 | return this.cVMemberCount; 77 | } 78 | 79 | public String getParents() { 80 | 81 | return this.parents; 82 | } 83 | 84 | public String getChildren() { 85 | 86 | return this.children; 87 | } 88 | 89 | public String getAncestors() { 90 | 91 | return this.ancestors; 92 | 93 | } 94 | 95 | public String getDescendants() { 96 | 97 | return this.descendants; 98 | } 99 | 100 | public String getDefinitions() { 101 | 102 | return this.definitions; 103 | } 104 | 105 | public String getRelations() { 106 | 107 | return this.relations; 108 | } 109 | 110 | public String getAttributes() { 111 | 112 | return this.attributes; 113 | } 114 | 115 | public String getDefaultPreferredAtom() { 116 | 117 | return this.defaultPreferredAtom; 118 | } 119 | 120 | private List> getSubsetMemberships() { 121 | 122 | return this.subsetMemberships; 123 | } 124 | 125 | private List> getContentViewMemberships() { 126 | 127 | return this.contentViewMemberships; 128 | } 129 | 130 | private void setAtoms(String atoms) { 131 | 132 | this.atoms = atoms; 133 | } 134 | 135 | private void setAtomCount(int atomCount) { 136 | 137 | this.atomCount = atomCount; 138 | } 139 | 140 | private void setcVMemberCount(int cVMemberCount) { 141 | 142 | this.cVMemberCount = cVMemberCount; 143 | } 144 | 145 | private void setUi(String ui) { 146 | 147 | this.ui = ui; 148 | } 149 | 150 | private void setConcepts(String concepts) { 151 | 152 | this.concepts = concepts; 153 | } 154 | 155 | private void setName(String name){ 156 | 157 | this.name=name; 158 | } 159 | 160 | private void setRootSource(String rootSource) { 161 | 162 | this.rootSource = rootSource; 163 | } 164 | 165 | private void setObsolete(boolean obsolete) { 166 | 167 | this.obsolete = obsolete; 168 | } 169 | 170 | private void setSuppressible(boolean suppressible) { 171 | 172 | this.suppressible = suppressible; 173 | } 174 | 175 | private void setDefinitions (String definitions) { 176 | 177 | this.definitions = definitions; 178 | } 179 | 180 | private void setRelations (String relations) { 181 | 182 | this.relations = relations; 183 | } 184 | 185 | private void setChildren(String children) { 186 | 187 | this.children = children; 188 | } 189 | 190 | 191 | private void setParents(String parents) { 192 | 193 | this.parents = parents; 194 | } 195 | 196 | private void setAncestors(String ancestors) { 197 | 198 | this.ancestors = ancestors; 199 | } 200 | 201 | private void setAttributes(String attributes) { 202 | 203 | this.attributes = attributes; 204 | 205 | } 206 | 207 | private void setDefaultPreferredAtom(String defaultPreferredAtom) { 208 | 209 | this.defaultPreferredAtom = defaultPreferredAtom; 210 | } 211 | 212 | private void setContentViewMemberships(List> contentViewMemberships) { 213 | 214 | this.contentViewMemberships = contentViewMemberships; 215 | 216 | } 217 | 218 | private void setSubsetMemberships(List> subsetMemberships) { 219 | 220 | this.subsetMemberships = subsetMemberships; 221 | 222 | } 223 | } 224 | -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/content/RetrieveAtomsTestCase.java: -------------------------------------------------------------------------------- 1 | /*This example allows you to retrieve atoms for a known CUI or source-asserted identifier in the UMLS 2 | You can run this class as a Junit4 test case - be sure and put each of the arguments as VM arguments 3 | in your runtime configuration, such as -Dapikey -Did=C0155502. 4 | To retrieve atoms that belong to a source-asserted concept, descriptor, or code, use the 5 | -Dsource parameter, such as -Dsource=SNOMEDCT_US 6 | */ 7 | package uts.rest.samples.content; 8 | import uts.rest.samples.classes.AtomLite; 9 | import uts.rest.samples.util.RestTicketClient; 10 | 11 | import org.junit.Test; 12 | 13 | import com.jayway.jsonpath.Configuration; 14 | import com.jayway.jsonpath.JsonPath; 15 | import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; 16 | import com.jayway.restassured.RestAssured; 17 | import com.jayway.restassured.response.Response; 18 | 19 | import static com.jayway.restassured.RestAssured.given; 20 | import static org.junit.Assert.*; 21 | 22 | 23 | public class RetrieveAtomsTestCase { 24 | 25 | //String username = System.getProperty("username"); 26 | //String password = System.getProperty("password"); 27 | String apiKey = System.getProperty("apikey"); 28 | String id = System.getProperty("id"); 29 | String source = System.getProperty("source"); 30 | //specifying version is not required - if you leave it out the script will default to the latest UMLS publication. 31 | String version = System.getProperty("version"); 32 | RestTicketClient ticketClient = new RestTicketClient(apiKey); 33 | //get a ticket granting ticket for this session. 34 | String tgt = ticketClient.getTgt(); 35 | 36 | @Test 37 | public void RetrieveAtoms() throws Exception { 38 | 39 | version = System.getProperty("version") == null ? "current": System.getProperty("version"); 40 | //if you do not specify a source vocabulary, the script assumes you're searching for CUI 41 | String path = System.getProperty("source") == null ? "/rest/content/"+version+"/CUI/"+id+"/atoms" : "/rest/content/"+version+"/source/"+source+"/"+id+"/atoms"; 42 | AtomLite[] atoms; 43 | int page = 1; 44 | int pageCount; 45 | int numberOfAtoms = 0; 46 | //UMLS CUI may have hundreds of atoms, so we've set up a way to page through them here. 47 | do { 48 | 49 | System.out.println("Page "+page); 50 | System.out.println("***********"); 51 | RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; 52 | Response response = given()//.log().all() 53 | .request().with() 54 | //we need a new service ticket for each call since we're requesting multiple pages. 55 | .param("ticket", ticketClient.getST(tgt)) 56 | //.param("language", "ENG") 57 | //.param("ttys","PT") 58 | //.param("sabs","SNOMEDCT_US") 59 | .param("pageNumber",page) 60 | .expect() 61 | .statusCode(200) 62 | .when().get(path); 63 | //response.then().log().all();; 64 | 65 | String output = response.getBody().asString(); 66 | Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); 67 | pageCount = JsonPath.using(config).parse(output).read("$.pageCount"); 68 | atoms = JsonPath.using(config).parse(output).read("$.result",AtomLite[].class); 69 | 70 | for(AtomLite atom:atoms) { 71 | 72 | System.out.println("AUI: "+ atom.getUi()); 73 | System.out.println("Name: " + atom.getName()); 74 | System.out.println("Term Type: " + atom.getTermType()); 75 | System.out.println("Obsolete: " + atom.getObsolete()); 76 | System.out.println("Vocabulary: " + atom.getRootSource()); 77 | System.out.println("UMLS Concept: " + atom.getConcept()); 78 | System.out.println("Source Concept: " + atom.getSourceConcept()); 79 | System.out.println("Source Descriptor: " + atom.getSourceDescriptor()); 80 | System.out.println("Source Code: " + atom.getCode()); 81 | System.out.println("-------"); 82 | } 83 | 84 | numberOfAtoms += atoms.length; 85 | page++; 86 | 87 | assertTrue(atoms.length > 0); 88 | 89 | } 90 | 91 | while(page <= pageCount ); 92 | 93 | System.out.println("Retrieved " + numberOfAtoms +" atoms for " + id); 94 | } 95 | 96 | 97 | } 98 | -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/content/RetrieveCodeTestCase.java: -------------------------------------------------------------------------------- 1 | /*This example allows you to retrieve information about a known source-asserted identifier. 2 | You can run this class as a Junit4 test case - be sure and put each of the arguments as VM arguments 3 | in your runtime configuration, such as -Dapikey -Did=9468002 -Dsource=SNOMEDCT_US 4 | */ 5 | 6 | package uts.rest.samples.content; 7 | import uts.rest.samples.util.RestTicketClient; 8 | import uts.rest.samples.classes.SourceAtomClusterLite; 9 | 10 | import org.junit.Test; 11 | 12 | import com.jayway.jsonpath.Configuration; 13 | import com.jayway.jsonpath.JsonPath; 14 | import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; 15 | import com.jayway.restassured.RestAssured; 16 | import com.jayway.restassured.response.Response; 17 | 18 | import static com.jayway.restassured.RestAssured.given; 19 | import static org.apache.commons.lang.StringUtils.join; 20 | 21 | 22 | public class RetrieveCodeTestCase { 23 | 24 | //String username = System.getProperty("username"); 25 | //String password = System.getProperty("password"); 26 | String apiKey = System.getProperty("apikey"); 27 | String id = System.getProperty("id"); 28 | String version = System.getProperty("version"); 29 | String source = System.getProperty("source"); 30 | RestTicketClient ticketClient = new RestTicketClient(apiKey); 31 | //get a ticket granting ticket for this session. 32 | String tgt = ticketClient.getTgt(); 33 | 34 | @Test 35 | public void RetrieveCodes() throws Exception { 36 | 37 | //if you omit the -Dversion parameter, use 'current' as the default. 38 | version = System.getProperty("version") == null ? "current": System.getProperty("version"); 39 | String path = "/rest/content/"+version+"/source/"+source+"/"+id; 40 | RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; 41 | Response response = given().log().all() 42 | .request().with() 43 | .param("ticket", ticketClient.getST(tgt)) 44 | .expect() 45 | .statusCode(200) 46 | .when().get(path); 47 | //response.then().log().all();; 48 | String output = response.getBody().asString(); 49 | Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); 50 | SourceAtomClusterLite code = JsonPath.using(config).parse(output).read("$.result",SourceAtomClusterLite.class); 51 | 52 | System.out.println(source+" code: " +code.getUi()+": "+code.getName()); 53 | System.out.println("Number of Atoms: " + code.getAtomCount()); 54 | System.out.println("Atoms: "+code.getAtoms()); 55 | System.out.println("Relations: "+code.getRelations()); 56 | System.out.println("Parents: "+code.getParents()); 57 | System.out.println("Children: "+code.getChildren()); 58 | System.out.println("Ancestors: "+code.getAncestors()); 59 | System.out.println("Descendants: "+code.getDescendants()); 60 | System.out.println("Highest Ranking Atom: "+code.getDefaultPreferredAtom()); 61 | 62 | 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/content/RetrieveCuiTestCase.java: -------------------------------------------------------------------------------- 1 | /*This example allows you to retrieve information about a known UMLS CUI. 2 | Examples are at https://github.com/jayway/rest-assured/tree/master/examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java 3 | You can run this class as a Junit4 test case - be sure and put each of the arguments as VM arguments 4 | in your runtime configuration, such as -Dapikey=12345-abcdef -Did=C0018787 5 | */ 6 | 7 | package uts.rest.samples.content; 8 | import uts.rest.samples.util.RestTicketClient; 9 | import uts.rest.samples.classes.ConceptLite; 10 | import org.junit.Test; 11 | import com.jayway.jsonpath.Configuration; 12 | import com.jayway.jsonpath.JsonPath; 13 | import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; 14 | import com.jayway.restassured.RestAssured; 15 | import com.jayway.restassured.response.Response; 16 | import static com.jayway.restassured.RestAssured.given; 17 | import static org.apache.commons.lang.StringUtils.join; 18 | 19 | 20 | public class RetrieveCuiTestCase { 21 | 22 | //String username = System.getProperty("username"); 23 | //String password = System.getProperty("password"); 24 | String apiKey = System.getProperty("apikey"); 25 | String id = System.getProperty("id"); 26 | String version = System.getProperty("version"); 27 | RestTicketClient ticketClient = new RestTicketClient(apiKey); 28 | //get a ticket granting ticket for this session. 29 | String tgt = ticketClient.getTgt(); 30 | 31 | @Test 32 | public void RetrieveCui() throws Exception { 33 | 34 | //if you omit the -Dversion parameter, use 'current' as the default. 35 | version = System.getProperty("version") == null ? "current": System.getProperty("version"); 36 | String path = "/rest/content/"+version+"/CUI/"+id; 37 | RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; 38 | Response response = given().log().all() 39 | .request().with() 40 | .param("ticket", ticketClient.getST(tgt)) 41 | .expect() 42 | .statusCode(200) 43 | .when().get(path); 44 | //response.then().log().all();; 45 | String output = response.getBody().asString(); 46 | Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); 47 | ConceptLite conceptLite = JsonPath.using(config).parse(output).read("$.result",ConceptLite.class); 48 | 49 | System.out.println(conceptLite.getUi()+": "+conceptLite.getName()); 50 | System.out.println("Semantic Type(s): "+ join(conceptLite.getSemanticTypes(),",")); 51 | System.out.println("Number of Atoms: " + conceptLite.getAtomCount()); 52 | System.out.println("Atoms: "+conceptLite.getAtoms()); 53 | System.out.println("Definitions: "+conceptLite.getDefinitions()); 54 | System.out.println("Relations: "+conceptLite.getRelations()); 55 | System.out.println("Highest Ranking Atom: "+conceptLite.getDefaultPreferredAtom()); 56 | 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/content/WalkHierarchyTestCase.java: -------------------------------------------------------------------------------- 1 | package uts.rest.samples.content; 2 | import uts.rest.samples.classes.AtomLite; 3 | import uts.rest.samples.classes.SourceAtomClusterLite; 4 | import uts.rest.samples.util.RestTicketClient; 5 | 6 | import org.junit.Test; 7 | 8 | import com.jayway.jsonpath.Configuration; 9 | import com.jayway.jsonpath.JsonPath; 10 | import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; 11 | import com.jayway.restassured.RestAssured; 12 | import com.jayway.restassured.response.Response; 13 | 14 | import static com.jayway.restassured.RestAssured.given; 15 | import static org.junit.Assert.*; 16 | 17 | public class WalkHierarchyTestCase { 18 | 19 | //String username = System.getProperty("username"); 20 | //String password = System.getProperty("password"); 21 | String apiKey = System.getProperty("apikey"); 22 | String id = System.getProperty("id"); 23 | String source = System.getProperty("source"); 24 | //specifying version is not required - if you leave it out the script will default to the latest UMLS publication. 25 | String version = System.getProperty("version"); 26 | //use either 'parents', 'children', 'ancestors', or 'descendants' here 27 | String operation = System.getProperty("operation"); 28 | RestTicketClient ticketClient = new RestTicketClient(apiKey); 29 | //get a ticket granting ticket for this session. 30 | String tgt = ticketClient.getTgt(); 31 | 32 | @Test 33 | public void WalkHierarchy() throws Exception { 34 | 35 | version = System.getProperty("version") == null ? "current": System.getProperty("version"); 36 | //if you do not specify a source vocabulary, the script assumes you're searching for CUI 37 | String path = "/rest/content/"+version+"/source/"+source+"/"+id+"/"+operation; 38 | SourceAtomClusterLite[] sourceAtomClusters; 39 | AtomLite[] atoms; 40 | int page=1; 41 | int results = 0; 42 | int pageCount; 43 | //calls to descendants may produce several hundred or even several thousand results. 44 | //so we page through them here. 45 | do { 46 | System.out.println("Page "+page); 47 | System.out.println("***********"); 48 | RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; 49 | Response response = given()//.log().all() 50 | .request().with() 51 | //we need a new service ticket for each call since we're requesting multiple pages. 52 | .param("ticket", ticketClient.getST(tgt)) 53 | .param("pageNumber",page) 54 | .expect() 55 | .statusCode(200) 56 | .when().get(path); 57 | //response.then().log().all();; 58 | 59 | String output = response.getBody().asString(); 60 | Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); 61 | pageCount = JsonPath.using(config).parse(output).read("$.pageCount"); 62 | 63 | //the HL7 sources return Atom objects, rather than SourceAtomClusters 64 | if(source.equals("HL7V3.0") || source.equals("HL7V2.5")) { 65 | 66 | atoms = JsonPath.using(config).parse(output).read("$.result",AtomLite[].class); 67 | 68 | for (AtomLite atom:atoms) { 69 | System.out.println("Ui: " + atom.getUi()); 70 | System.out.println("Name: "+ atom.getName()); 71 | System.out.println("Code: " + atom.getCode()); 72 | System.out.println("Parents: "+ atom.getParents()); 73 | System.out.println("Children: " + atom.getChildren()); 74 | System.out.println("-------"); 75 | 76 | } 77 | 78 | results += atoms.length; 79 | } 80 | else { 81 | 82 | sourceAtomClusters = JsonPath.using(config).parse(output).read("$.result",SourceAtomClusterLite[].class); 83 | 84 | for(SourceAtomClusterLite sourceAtomCluster:sourceAtomClusters) { 85 | 86 | System.out.println("Ui: "+sourceAtomCluster.getUi()); 87 | System.out.println("Name: "+sourceAtomCluster.getName()); 88 | System.out.println("Number of Atoms: "+sourceAtomCluster.getAtomCount()); 89 | System.out.println("Concepts: "+sourceAtomCluster.getConcepts()); 90 | System.out.println("Ancestors: "+sourceAtomCluster.getAncestors()); 91 | System.out.println("Parents: "+ sourceAtomCluster.getParents()); 92 | System.out.println("Children: "+sourceAtomCluster.getChildren()); 93 | System.out.println("Descendants: "+sourceAtomCluster.getDescendants()); 94 | System.out.println("Highest Ranking Atom: "+sourceAtomCluster.getDefaultPreferredAtom()); 95 | System.out.println("-------"); 96 | } 97 | 98 | results += sourceAtomClusters.length; 99 | } 100 | 101 | page++; 102 | 103 | //assertTrue(sourceAtomClusters.length > 0); 104 | 105 | } while(page <= pageCount ); 106 | System.out.println("Found " + results + " results"); 107 | 108 | } 109 | 110 | } 111 | 112 | -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/cookbook/CodeCrosswalk.java: -------------------------------------------------------------------------------- 1 | /*This example loads a file of hpo identifiers(hpo-codes.txt from the 'resources' folder) 2 | * and retrieves SNOMED CT preferred terms 3 | * that live in the same UMLS CUI as the HPO identifier. 4 | */ 5 | package uts.rest.samples.cookbook; 6 | import java.io.BufferedReader; 7 | import java.io.FileReader; 8 | 9 | import uts.rest.samples.util.RestTicketClient; 10 | import uts.rest.samples.classes.*; 11 | 12 | import org.junit.Test; 13 | 14 | import com.jayway.jsonpath.Configuration; 15 | import com.jayway.jsonpath.JsonPath; 16 | import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; 17 | import com.jayway.restassured.RestAssured; 18 | import com.jayway.restassured.response.Response; 19 | 20 | import static com.jayway.restassured.RestAssured.given; 21 | 22 | public class CodeCrosswalk { 23 | 24 | //String username = System.getProperty("username"); 25 | //String password = System.getProperty("password"); 26 | String apiKey = System.getProperty("apikey"); 27 | String version = System.getProperty("version"); 28 | RestTicketClient ticketClient = new RestTicketClient(apiKey); 29 | //get a ticket granting ticket for this session. 30 | String tgt = ticketClient.getTgt(); 31 | SourceAtomClusterLite[] sourceAtomClusters; 32 | 33 | @Test 34 | public void RunCrosswalk() throws Exception { 35 | 36 | version = System.getProperty("version") == null ? "current": System.getProperty("version"); 37 | System.out.println("HPO Id|SNOMEDCT ConceptId|SNOMEDCT Name"); 38 | try (BufferedReader br = new BufferedReader(new FileReader("resources/hpo-codes.txt"))) { 39 | String hpo; 40 | 41 | while ((hpo = br.readLine()) != null) { 42 | 43 | try { 44 | sourceAtomClusters = CrossWalkCodes(hpo, "SNOMEDCT_US"); 45 | for (SourceAtomClusterLite sourceAtomCluster:sourceAtomClusters) { 46 | 47 | System.out.println(hpo+"|"+sourceAtomCluster.getUi()+"|"+ sourceAtomCluster.getName()); 48 | 49 | } 50 | 51 | } 52 | catch (Exception ex) { 53 | //cannot find a CUI-based match to SNOMED CT 54 | System.out.println(hpo + "||"); 55 | 56 | } 57 | 58 | } 59 | 60 | } 61 | } 62 | 63 | 64 | public SourceAtomClusterLite[] CrossWalkCodes(String code, String targetSource) { 65 | RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; 66 | String path = "/rest/crosswalk/"+version+"/source/HPO/"+code; 67 | 68 | Response response = given()//.log().all() 69 | .request().with() 70 | .param("ticket", ticketClient.getST(tgt)) 71 | .param("targetSource", "SNOMEDCT_US") 72 | .when().get(path); 73 | 74 | String output = response.getBody().asString(); 75 | Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); 76 | sourceAtomClusters = JsonPath.using(config).parse(output).read("$.result",SourceAtomClusterLite[].class); 77 | return sourceAtomClusters; 78 | 79 | } 80 | 81 | } 82 | 83 | 84 | -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/search/BatchTermToCuiOrCodeTestCase.java: -------------------------------------------------------------------------------- 1 | /*This example loads a file of disease names (findings.txt from the 'resources' folder) 2 | * and retrieves the relevant UMLS CUI(s) or source-asserted codes 3 | */ 4 | package uts.rest.samples.search; 5 | import java.io.BufferedReader; 6 | import java.io.FileReader; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import uts.rest.samples.util.RestTicketClient; 11 | import uts.rest.samples.classes.SearchResult; 12 | 13 | import org.junit.Test; 14 | 15 | import com.jayway.jsonpath.Configuration; 16 | import com.jayway.jsonpath.JsonPath; 17 | import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; 18 | import com.jayway.restassured.RestAssured; 19 | import com.jayway.restassured.response.Response; 20 | 21 | import static com.jayway.restassured.RestAssured.given; 22 | 23 | 24 | public class BatchTermToCuiOrCodeTestCase { 25 | 26 | //String username = System.getProperty("username"); 27 | //String password = System.getProperty("password"); 28 | String apiKey = System.getProperty("apikey"); 29 | String version = System.getProperty("version"); 30 | RestTicketClient ticketClient = new RestTicketClient(apiKey); 31 | //get a ticket granting ticket for this session. 32 | String tgt = ticketClient.getTgt(); 33 | 34 | 35 | @Test 36 | public void RetrieveCuis() throws Exception { 37 | 38 | version = System.getProperty("version") == null ? "current": System.getProperty("version"); 39 | try (BufferedReader br = new BufferedReader(new FileReader("resources/findings.txt"))) { 40 | String line; 41 | 42 | while ((line = br.readLine()) != null) { 43 | List results = SearchTerm(line); 44 | if (results.size() == 0){System.out.println("No results for "+ line);} 45 | int num = 1; 46 | for(SearchResult result:results) { 47 | 48 | String cui = result.getUri(); 49 | String name = result.getName(); 50 | String rsab = result.getRootSource(); 51 | 52 | System.out.println("Result "+ num); 53 | System.out.println("cui:"+ cui); 54 | System.out.println("name:"+ name); 55 | System.out.println("Highest ranking source of cui:" + rsab); 56 | num++; 57 | } 58 | System.out.println("----------"); 59 | 60 | } 61 | 62 | } 63 | } 64 | 65 | public List SearchTerm(String term) throws Exception { 66 | 67 | version = System.getProperty("version") == null ? "current": System.getProperty("version"); 68 | int pageNumber = 0; 69 | SearchResult[] results; 70 | List holder = new ArrayList(); 71 | do { 72 | pageNumber++; 73 | RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; 74 | Response response = given()//.log().all() 75 | .request().with() 76 | .param("ticket", ticketClient.getST(tgt)) 77 | .param("string", term) 78 | .param("pageNumber",pageNumber) 79 | //uncomment below to return only CUIs that have at least one non-obsolete/non-suppressible atom (relevant to the searchType) from the US Edition of SNOMED CT 80 | //.param("sabs","SNOMEDCT_US") 81 | //uncomment below to return CUIs that have at least one non-obsolete/non-suppressible atom that is an exact match with the search term 82 | //.param("searchType","exact") //valid values are exact,words, approximate,leftTruncation,rightTruncation, and normalizedString 83 | //uncomment below to return source-asserted identifiers (from SNOMEDCT and other UMLS vocabularies) instead of CUIs 84 | //.param("returnIdType","code") 85 | .expect() 86 | .statusCode(200) 87 | .when().get("/rest/search/"+version); 88 | 89 | String output = response.getBody().asString(); 90 | Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); 91 | results = JsonPath.using(config).parse(output).read("$.result.results",SearchResult[].class); 92 | 93 | //the /search endpoint returns an array of 'result' objects 94 | //See http://documentation.uts.nlm.nih.gov/rest/search/index.html#sample-output for a complete list of fields output under the /search endpoint 95 | for(SearchResult result:results) { 96 | 97 | if (!results[0].getUi().equals("NONE")){holder.add(result);} 98 | } 99 | 100 | }while(!results[0].getUi().equals("NONE")); 101 | return holder; 102 | 103 | } 104 | } 105 | 106 | 107 | -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/search/SearchTermsTestCase.java: -------------------------------------------------------------------------------- 1 | package uts.rest.samples.search; 2 | import uts.rest.samples.classes.SearchResult; 3 | import uts.rest.samples.util.RestTicketClient; 4 | 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | 9 | import org.junit.Test; 10 | 11 | import com.jayway.jsonpath.Configuration; 12 | import com.jayway.jsonpath.JsonPath; 13 | import com.jayway.restassured.RestAssured; 14 | import com.jayway.restassured.response.Response; 15 | import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; 16 | 17 | import static com.jayway.restassured.RestAssured.given; 18 | import static com.jayway.restassured.path.json.JsonPath.with; 19 | import static com.jayway.jsonpath.JsonPath.read; 20 | 21 | /*This example allows you to search terms in the UMLS 22 | Examples are at https://github.com/jayway/rest-assured/tree/master/examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java 23 | For convenience, google's quick json parser is also included in the pom.xml file: 24 | https://code.google.com/p/quick-json/ 25 | You can run this class as a Junit4 test case - be sure and put each of the arguments as VM arguments 26 | You may page through results returned from the /search endpoint until you reach the null 'ui:NONE' or 'name:NO RESULTS'. These results will always be a single result on their own page. 27 | in your runtime configuration, such as -Dapikey -Dterm = "diabetic foot" 28 | 29 | */ 30 | 31 | public class SearchTermsTestCase { 32 | 33 | //String username = System.getProperty("username"); 34 | //String password = System.getProperty("password"); 35 | String apiKey = System.getProperty("apikey"); 36 | //version is not a required argument - if left out you will search against the latest UMLS publication 37 | String version = System.getProperty("version"); 38 | String term = System.getProperty("term"); 39 | RestTicketClient ticketClient = new RestTicketClient(apiKey); 40 | //get a ticket granting ticket for this session. 41 | String tgt = ticketClient.getTgt(); 42 | 43 | 44 | @Test 45 | public void SearchTerm() throws Exception { 46 | 47 | version = System.getProperty("version") == null ? "current": System.getProperty("version"); 48 | 49 | 50 | int total = 0; 51 | int pageNumber = 0; 52 | SearchResult[] results; 53 | do { 54 | pageNumber++; 55 | System.out.println("Fetching results for page "+pageNumber); 56 | RestAssured.baseURI = "https://uts-ws.nlm.nih.gov"; 57 | Response response = given()//.log().all() 58 | .request().with() 59 | .param("ticket", ticketClient.getST(tgt)) 60 | .param("string", term) 61 | .param("pageNumber",pageNumber) 62 | //uncomment to return CUIs that have at least one matching term from the US Edition of SNOMED CT 63 | //.param("sabs", "SNOMEDCT_US") 64 | //uncomment to return SNOMED CT concepts rather than UMLS CUIs. 65 | //.param("returnIdType", "sourceConcept") 66 | //.param("searchType","exact") //valid values are exact,words, approximate,leftTruncation,rightTruncation, and normalizedString 67 | .expect() 68 | .statusCode(200) 69 | .when().get("/rest/search/"+version); 70 | 71 | String output = response.getBody().asString(); 72 | Configuration config = Configuration.builder().mappingProvider(new JacksonMappingProvider()).build(); 73 | results = JsonPath.using(config).parse(output).read("$.result.results",SearchResult[].class); 74 | 75 | //the /search endpoint returns an array of 'result' objects 76 | //See http://documentation.uts.nlm.nih.gov/rest/search/index.html#sample-output for a complete list of fields output under the /search endpoint 77 | for(SearchResult result:results) { 78 | 79 | String ui = result.getUi(); 80 | String name = result.getName(); 81 | String rootSource = result.getRootSource(); 82 | String uri = result.getUri(); 83 | System.out.println("ui: " + ui); 84 | System.out.println("name: " + name); 85 | System.out.println("rootSource: " + rootSource); 86 | System.out.println("uri: " + uri); 87 | 88 | System.out.println("**"); 89 | } 90 | System.out.println("----------"); 91 | total += results.length; 92 | }while(!results[0].getUi().equals("NONE")); 93 | //account for the one 'NO RESULTS' result :-/ 94 | total--; 95 | System.out.println("Found " + total+ " results for "+ term); 96 | 97 | 98 | 99 | 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /samples/java/src/test/java/uts/rest/samples/util/RestTicketClient.java: -------------------------------------------------------------------------------- 1 | package uts.rest.samples.util; 2 | import static com.jayway.restassured.RestAssured.given; 3 | import com.jayway.restassured.RestAssured; 4 | import com.jayway.restassured.response.Headers; 5 | import com.jayway.restassured.response.Response; 6 | 7 | public class RestTicketClient { 8 | 9 | private String tgt; 10 | private String st; 11 | private String service = "http://umlsks.nlm.nih.gov"; 12 | private String username = null; 13 | private String password = null; 14 | private String authUri = "https://utslogin.nlm.nih.gov"; 15 | private String apikey = null; 16 | 17 | public RestTicketClient (String username, String password) { 18 | 19 | this.username = username; 20 | this.password = password; 21 | } 22 | 23 | public RestTicketClient (String apikey) { 24 | this.apikey = apikey; 25 | } 26 | 27 | public String getTgt() 28 | 29 | { 30 | String tgt = null; 31 | if(this.username != null && this.password != null){ 32 | RestAssured.baseURI=authUri; 33 | Response response = given()//.log().all() 34 | .request().with() 35 | .param("username", username) 36 | .param("password", password) 37 | .expect() 38 | .statusCode(201) 39 | .when().post("/cas/v1/tickets"); 40 | 41 | Headers h = response.getHeaders(); 42 | tgt = h.getValue("location").substring(h.getValue("location").indexOf("TGT")); 43 | //response.then().log() 44 | 45 | } else if (apikey != null) { 46 | RestAssured.baseURI=authUri; 47 | Response response = given()//.log().all() 48 | .request().with() 49 | .param("apikey", apikey) 50 | .expect() 51 | .statusCode(201) 52 | .when().post("/cas/v1/api-key"); 53 | 54 | Headers h = response.getHeaders(); 55 | tgt = h.getValue("location").substring(h.getValue("location").indexOf("TGT")); 56 | } 57 | return tgt; 58 | } 59 | 60 | 61 | public String getST(String tgt) 62 | { 63 | RestAssured.baseURI=authUri; 64 | Response response = given()//.log().all() 65 | .request().with() 66 | .param("service", service) 67 | .expect() 68 | .statusCode(200) 69 | .when().post("/cas/v1/tickets/" + tgt); 70 | 71 | String st = response.getBody().asString(); 72 | //response.then().log().all(); 73 | return st; 74 | } 75 | 76 | public void logout(String ticket) 77 | { 78 | RestAssured.baseURI=authUri; 79 | Response response = given()//.log().all() 80 | .request().with() 81 | .param("service", service) 82 | .expect() 83 | .statusCode(200) 84 | .when().delete("/cas/v1/tickets/" + ticket); 85 | // response.then().log().all(); 86 | } 87 | 88 | 89 | 90 | 91 | 92 | } 93 | -------------------------------------------------------------------------------- /samples/perl/crosswalk.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl -w 2 | 3 | ## usage: perl crosswalk.pl -u your-umls-username -p your-umls-password -v source vocabulary -i source vocabulary identifier [ -r specify target vocabulary] 4 | ## Performs a crosswalk using the latest UMLS version and retrieves all codes that share a UMLS CUI with a particular code. 5 | ## Example: 6 | ## perl crosswalk.pl -u username -p password -v HPO -i HP:0001947 7 | ## perl crosswalk.pl -u username -p password -v HPO -i HP:0001947 -r SNOMEDCT_US 8 | ## More information: https://documentation.uts.nlm.nih.gov/rest/source-asserted-identifiers/crosswalk/index.html 9 | 10 | use lib "lib"; 11 | use strict; 12 | use URI; 13 | use Authentication::TicketClient; 14 | use JSON; 15 | use REST::Client; 16 | use Data::Dumper; 17 | use Getopt::Std; 18 | 19 | ## parse command line arguments 20 | our ($opt_u,$opt_p,$opt_v,$opt_i, $opt_r); 21 | getopt('upvir'); 22 | my $username = $opt_u || die "please provide username"; 23 | my $password = $opt_p || die "please provide password"; 24 | my $source = $opt_v || die "Please provide a source vocabulary"; 25 | my $identifier = $opt_i || die "Please provide a source vocabulary identifier"; 26 | 27 | ## Create a ticket granting ticket for the session 28 | my $ticketClient = 29 | new TicketClient(username=>$opt_u,password=>$opt_p,service=>"http://umlsks.nlm.nih.gov",tgt=>"") || die "could not create TicketClient() object"; 30 | my $tgt = $ticketClient->getTgt(); 31 | my $uri = new URI("https://uts-ws.nlm.nih.gov"); 32 | my $json; 33 | my $client = REST::Client->new(); 34 | my %parameters = (); 35 | 36 | my $path = sprintf("/rest/crosswalk/current/source/%s/%s", $opt_v, $opt_i); 37 | 38 | if ( defined $opt_r && $opt_r ){ 39 | $parameters{'targetSource'} = $opt_r 40 | } 41 | 42 | ## Query the API 43 | $json = run_query($path,\%parameters); 44 | my $ra_results = $json->{'result'}; 45 | 46 | ## Loop through results 47 | foreach my $result( @$ra_results ) { 48 | printf("%s %s %s\n", $result->{'rootSource'}, $result->{'ui'}, $result->{'name'} ) 49 | } 50 | 51 | 52 | sub format_json { 53 | my $json_in = shift; 54 | my $json = JSON->new; 55 | my $obj = $json->decode($json_in); 56 | return $obj; 57 | } 58 | 59 | sub run_query { 60 | my ($path, $parameters) = @_; 61 | $parameters{ticket} = $ticketClient->getServiceTicket(); 62 | $uri->path($path); 63 | $uri->query_form($parameters); 64 | print qq{$uri\n\n}; 65 | my $query = $client->GET($uri) || die "Could not execute query $!\n"; 66 | my $results = $query->responseCode() eq '200'? $query->responseContent: die "Could not execute query $!\n"; 67 | my $json = format_json($results); 68 | return $json; 69 | } 70 | -------------------------------------------------------------------------------- /samples/perl/lib/Authentication/TicketClient.pm: -------------------------------------------------------------------------------- 1 | ############################################################################################################################## 2 | # Version 1.0 - 7/28/2015 3 | # The ticket client has two methods: 4 | # getTgt() and getServiceTicket() 5 | # run getTgt() to obtain your ticket granting ticket. 6 | # run getServiceTicket() before each call to https://uts-ws.nlm.nih.gov/rest/content or other future endpoints... to obtain a service ticket 7 | # in your client script, include the line use Authentication::TicketClient; 8 | # make a new ticket client as follows: 9 | # my $ticketClient = new TicketClient(username=>"yourusername",password=>"yourpassword",service=>"http://umlsks.nlm.nih.gov",tgt=>""); 10 | ############################################################################################################################## 11 | 12 | use warnings; 13 | use LWP::UserAgent; 14 | use URI; 15 | use HTML::Form; 16 | 17 | package TicketClient; 18 | 19 | sub new { 20 | 21 | my ($class,%args) = @_; 22 | return bless { %args }, $class; 23 | 24 | } 25 | 26 | sub getTgt { 27 | 28 | my $self = shift; 29 | my $uri = URI->new("https://utslogin.nlm.nih.gov"); 30 | my $ua = LWP::UserAgent->new; 31 | $uri->path("/cas/v1/tickets"); 32 | my $query = $ua->post($uri, 33 | ['username'=>$self->{username}, 34 | 'password'=>$self->{password} 35 | ],); 36 | die "Error: ", $query->status_line unless $query->is_success; 37 | 38 | my @forms = HTML::Form->parse($query); 39 | my $form = $forms[0]; 40 | my $tgtUrl = $form->action; 41 | 42 | ##actually here we're not getting just the TGT, but the entire URL from the action attribute of the form 43 | ##returned in the call. This saves us from having to extract the TGT with substr or something else. 44 | ##assign the action attribute URL to the 'tgt' property of the TicketClient. 45 | $self->{tgt} = $tgtUrl; 46 | 47 | }## end getTgt 48 | 49 | sub getServiceTicket { 50 | 51 | my $self = shift; 52 | my $ua = LWP::UserAgent->new; 53 | my $uri = URI->new($self->{tgt}); 54 | my $query = $ua->post($uri, 55 | ['service'=>$self->{service} 56 | ],); 57 | die "Error: ", $query->status_line unless $query->is_success; 58 | 59 | my $st = $query->content; 60 | return $st; 61 | 62 | } 63 | ## end getServiceTicket 64 | 65 | 66 | 1; -------------------------------------------------------------------------------- /samples/perl/retrieve-atoms.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | ## Compatible with UMLS REST API - version 0.51 Beta 4 | ## usage: perl retrieve-atoms.pl -u your-umls-username -p your-umls-password -v version (optional) -i identifier -s source_vocabulary(optional) 5 | ## If you do not provide the version parameter the script queries the latest avaialble UMLS publication. 6 | ## This file takes a CUI or a source asserted identifier and retrieves atoms according to your query parameters. 7 | ## Use the -s flag to specify (optionally) a UMLS source vocabulary. If you omit this flag the script expects that your -i (identifier) argument will be 8 | ## populated with a UMLS CUI. 9 | ## The full list of fields available for search results is at https://documentation.uts.nlm.nih.gov/rest/atoms/index.html 10 | 11 | use lib "lib"; 12 | use strict; 13 | use warnings; 14 | use URI; 15 | use Authentication::TicketClient; 16 | use JSON; 17 | use REST::Client; 18 | use Data::Dumper; 19 | use Getopt::Std; 20 | our ($opt_u,$opt_p,$opt_v,$opt_i,$opt_s); 21 | getopt('upvsi'); 22 | my $username = $opt_u || die "please provide username"; 23 | my $password = $opt_p || die "please provide password"; 24 | my $version = defined $opt_v ? $opt_v : "current"; 25 | my $source = $opt_s; 26 | my $id = $opt_i || die "please provide an identifier"; 27 | 28 | ##create a ticket granting ticket for the session 29 | my $ticketClient = new TicketClient(username=>$opt_u,password=>$opt_p,service=>"http://umlsks.nlm.nih.gov",tgt=>"") || die "could not create TicketClient() object"; 30 | my $tgt = $ticketClient->getTgt(); 31 | my $uri = new URI("https://uts-ws.nlm.nih.gov"); 32 | my $json; 33 | my $client = REST::Client->new(); 34 | my $pageNum = 1; 35 | my $pageCount; 36 | my $resultCount = 0; 37 | my %parameters = (); 38 | my $obj; 39 | my $path = defined $source ? "/rest/content/".$version."/source/".$source."/".$id."/atoms": "/rest/content/".$version."/CUI/".$id."/atoms" ; 40 | my $result; 41 | 42 | ## with /atoms you may get more than the default 25 objects per page. You can either set your paging to higher values or page through results 43 | ## as in this example. 44 | do { 45 | 46 | $parameters{pageNumber} = $pageNum; 47 | #$parameters{sabs} = "SNOMEDCT_US"; 48 | $parameters{language} = "ENG"; 49 | ##suppressible/obsolete atoms are excluded by default 50 | #$parameters{includeSuppressible} = "true"; 51 | #$parameters{includeObsolete} = "true"; 52 | #$parameters{ttys} = "PT"; 53 | $json = run_query($path,\%parameters); 54 | $pageCount = $json->{pageCount}; 55 | print qq{On page $pageCount of $pageNum pages\n}; 56 | 57 | foreach my $atom(@{ $json->{result} }) { 58 | 59 | 60 | printf "%s\n","AUI: ".$atom->{ui}; 61 | printf "%s\n","Atom Name: ".$atom->{name}; 62 | printf "%s\n","Language: ".$atom->{language}; 63 | printf "%s\n","Term Type: ".$atom->{termType}; 64 | printf "%s\n","Obsolete: ".$atom->{obsolete}; 65 | printf "%s\n","Suppressible: ".$atom->{suppressible}; 66 | printf "%s\n", "Source: ".$atom->{rootSource}; 67 | printf "%s\n", "CUI: " .$atom->{memberships}->{concept}; 68 | ## The {memberships} wrapper returned by the /atoms endpoint contains information about to which source concept,code,or source descriptor the atom belongs 69 | ## not all vocabularies have source descriptors or source concepts, so we make sure they exist. 70 | printf "%s\n", "Source Concept: " .$atom->{memberships}->{sourceConcept} if defined $atom->{memberships}->{sourceConcept}; 71 | printf "%s\n", "Source Descriptor: " .$atom->{memberships}->{sourceDescriptor} if defined $atom->{memberships}->{sourceDescriptor}; 72 | printf "%s\n", "Code: " .$atom->{memberships}->{code} if defined $atom->{memberships}->{code}; 73 | print qq{\n}; 74 | 75 | } 76 | print qq{-------\n}; 77 | $pageNum++; 78 | $resultCount += scalar((@{ $json->{result} })); 79 | } 80 | ##page all the way through until the end. 81 | while ($pageNum < ($pageCount + 1)); 82 | print qq{Found $resultCount total results\n}; 83 | 84 | 85 | sub format_json { 86 | my $json_in = shift; 87 | my $json = JSON->new; 88 | my $obj = $json->decode($json_in); 89 | #print Dumper(\$obj); 90 | return $obj; 91 | } 92 | 93 | sub run_query { 94 | 95 | my ($path, $parameters) = @_; 96 | $parameters{ticket} = $ticketClient->getServiceTicket(); 97 | $uri->path($path); 98 | $uri->query_form($parameters); 99 | print qq{$uri\n\n}; 100 | my $query = $client->GET($uri) || die "Could not execute query$!"; 101 | my $results = $query->responseCode() eq '200'? $query->responseContent: die "Could not execute query$!"; 102 | my $json = format_json($results); 103 | return $json; 104 | } 105 | 106 | -------------------------------------------------------------------------------- /samples/perl/retrieve-cui-or-code.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | ## Compatible with UMLS REST API - version 0.60 Beta 4 | ## This file retrieves basic information of a source-asserted identifer or UMLS CUI. 5 | ## usage: perl retrieve-concept-info.pl -u your-umls-username -p your-umls-password -v version -i identifer -s source vocabulary 6 | ## If you do not provide the version parameter the script queries the latest avaialble UMLS publication. 7 | ## To query the UMLS, omit the 'source' parameter and use UMLS CUI as your 'identifier' parameter. 8 | ## The full list of query parameters and fields available for CUI retrieval is at: 9 | ## https://documentation.uts.nlm.nih.gov/rest/concept/index.html and 10 | ## https://documentation.uts.nlm.nih.gov/rest/source-asserted-identifiers/index.html 11 | 12 | use lib "lib"; 13 | use strict; 14 | use warnings; 15 | use URI; 16 | use Authentication::TicketClient; 17 | use JSON; 18 | use REST::Client; 19 | use Data::Dumper; 20 | use Getopt::Std; 21 | our ($opt_u,$opt_p,$opt_v,$opt_s, $opt_i); 22 | getopt('upvsi'); 23 | my $username = $opt_u || die "please provide username"; 24 | my $password = $opt_p || die "please provide password"; 25 | my $id = $opt_i || die "please provide a UMLS CUI or source-asserted identifier"; 26 | my $version = defined $opt_v ? $opt_v : "current"; 27 | my $source = $opt_s; 28 | 29 | 30 | ##create a ticket granting ticket for the session 31 | my $ticketClient = new TicketClient(username=>$opt_u,password=>$opt_p,service=>"http://umlsks.nlm.nih.gov",tgt=>"") || die "could not create TicketClient() object"; 32 | my $tgt = $ticketClient->getTgt(); 33 | my $uri = new URI("https://uts-ws.nlm.nih.gov"); 34 | my %parameters = (); 35 | my $client = REST::Client->new(); 36 | 37 | 38 | my $path = defined $source ? "/rest/content/".$version."/source/".$source."/".$id : "/rest/content/".$version."/CUI/".$id; 39 | my $json = run_query($path,\%parameters); 40 | my $cuiOrCode = $json->{result}; 41 | 42 | printf "%s\n","ui- ".$cuiOrCode->{ui}; 43 | printf "%s\n","Number of Atoms- ".$cuiOrCode->{atomCount}; 44 | printf "%s\n","Name- ".$cuiOrCode->{name}; 45 | printf "%s\n","Atoms- ".$cuiOrCode->{atoms}; 46 | printf "%s\n","Definitions- ".$cuiOrCode->{definitions}; 47 | printf "%s\n","Relations- ".$cuiOrCode->{relations}; 48 | printf "%s\n","Highest Ranking Atom- ".$cuiOrCode->{defaultPreferredAtom}; 49 | my $stys = $cuiOrCode->{semanticTypes}; 50 | 51 | ## Semantic Types are only assigned to UMLS CUIs. There are often more than one semantic type per CUI. 52 | if (!defined $source) { 53 | 54 | printf "%s\n", "Semantic Types:"; 55 | foreach my $sty (@{ $stys }) { 56 | printf "%s\n", "uri: ".$sty->{uri}; 57 | printf "%s\n", "name: ".$sty->{name}; 58 | 59 | } 60 | } 61 | ##source-asserted data. UMLS CUIs do not have transitive relations. 62 | printf "%s\n","Parents- ".$cuiOrCode->{parents} if defined $source; 63 | printf "%s\n","Children- ".$cuiOrCode->{children} if defined $source; 64 | printf "%s\n","Ancestors- ".$cuiOrCode->{ancestors} if defined $source; 65 | printf "%s\n","Descendants- ".$cuiOrCode->{descendants} if defined $source; 66 | 67 | 68 | 69 | sub format_json { 70 | my $json_in = shift; 71 | my $json = JSON->new; 72 | my $obj = $json->decode($json_in); 73 | #print Dumper(\$obj); 74 | return $obj; 75 | } 76 | 77 | sub run_query { 78 | 79 | my ($path, $parameters) = @_; 80 | $parameters{ticket} = $ticketClient->getServiceTicket(); 81 | $uri->path($path); 82 | $uri->query_form($parameters); 83 | print qq{$uri\n}; 84 | my $query = $client->GET($uri) || die "Could not execute query$!"; 85 | my $results = $query->responseCode() eq '200'? $query->responseContent: die "Could not execute query$!"; 86 | my $json = format_json($results); 87 | return $json; 88 | } 89 | -------------------------------------------------------------------------------- /samples/perl/search-terms.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | ##usage: perl search-terms.pl -u your-umls-username -p your-umls-password -v version -s string 4 | ##If you do not provide the version parameter the script queries the latest avaialble UMLS publication. 5 | ##Use quotes if your search string has spaces, for example perl search-terms.pl -u username -p password -s "diabetic foot" 6 | ##This file searches the UMLS against a string you provide returns CUIs (by default) or source-asserted identifers. 7 | ##The full list of fields available for search results is at https://documentation.uts.nlm.nih.gov/rest/search/index.html 8 | 9 | use lib "lib"; 10 | use strict; 11 | use warnings; 12 | use URI; 13 | use Authentication::TicketClient; 14 | use JSON; 15 | use REST::Client; 16 | use Data::Dumper; 17 | use Getopt::Std; 18 | our ($opt_u,$opt_p,$opt_v,$opt_s); 19 | getopt('upvs'); 20 | my $username = $opt_u || die "please provide username"; 21 | my $password = $opt_p || die "please provide password"; 22 | my $version = defined $opt_v ? $opt_v : "current"; 23 | my $string = $opt_s || die "please provide a query string"; 24 | my $resultCount = 0; 25 | 26 | ##create a ticket granting ticket for the session 27 | my $ticketClient = new TicketClient(username=>$opt_u,password=>$opt_p,service=>"http://umlsks.nlm.nih.gov",tgt=>"") || die "could not create TicketClient() object"; 28 | my $tgt = $ticketClient->getTgt(); 29 | my $uri = new URI("https://uts-ws.nlm.nih.gov"); 30 | my $json; 31 | my $client = REST::Client->new(); 32 | my %parameters = (); 33 | 34 | my $pageNum = "1"; 35 | my $path = "/rest/search/".$version; 36 | $parameters{string} = $string; 37 | #$parameters{searchType} = "exact"; 38 | ##optional parameters to return source-asserted identifiers and filter by source. You can also use 'sourceConcept' (for SNOMEDCT_US, LNC, NCI,RXNORM) or 'sourceDescriptor' (for MSH,MDR,ICD9CM,ICD10CM,GO) 39 | #$parameters{returnIdType} = "code"; 40 | $parameters{sabs} = "SNOMEDCT_US"; 41 | 42 | print qq{Searching term $string\n}; 43 | #many term searches will return more than the default page size, which is 25 json objects, so we page through them here. 44 | do { 45 | $parameters{pageNumber} = $pageNum; 46 | #$parameters{pageSize} = "10"; 47 | print qq{Page $pageNum Results\n}; 48 | $json = run_query($path,\%parameters); 49 | foreach my $result(@{ $json->{result}{results} }) { 50 | 51 | printf "%s\n","uri: ".$result->{uri} if defined $result->{uri}; 52 | printf "%s\n","ui: ".$result->{ui} if $result->{ui} ne 'NONE'; 53 | printf "%s\n","name: ".$result->{name} if $result->{name} ne 'NO RESULTS'; 54 | printf "%s\n","Source Vocabulary: ".$result->{rootSource} if defined $result->{rootSource}; 55 | print qq{\n}; 56 | } 57 | print qq{----------\n}; 58 | $pageNum++; 59 | $resultCount+= scalar(@{ $json->{result}{results} }); 60 | 61 | } 62 | 63 | ##TODO: Add 'next' and 'previous' page URIs to JSON output so we don't have to do this:. 64 | while $json->{result}{results}[0]{name} ne 'NO RESULTS'; 65 | ### paging is not fully implemented under the /search endpoint, so we have to discount the one 'NO RESULTS' result. 66 | $resultCount--; 67 | print qq{Found $resultCount results\n}; 68 | 69 | 70 | sub format_json { 71 | my $json_in = shift; 72 | my $json = JSON->new; 73 | my $obj = $json->decode($json_in); 74 | #print Dumper(\$obj); 75 | return $obj; 76 | } 77 | 78 | sub run_query { 79 | 80 | my ($path, $parameters) = @_; 81 | $parameters{ticket} = $ticketClient->getServiceTicket(); 82 | $uri->path($path); 83 | $uri->query_form($parameters); 84 | print qq{$uri\n\n}; 85 | my $query = $client->GET($uri) || die "Could not execute query $!\n"; 86 | my $results = $query->responseCode() eq '200'? $query->responseContent: die "Could not execute query $!\n"; 87 | my $json = format_json($results); 88 | return $json; 89 | } 90 | 91 | -------------------------------------------------------------------------------- /samples/perl/walk-hierarchy.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | ## Compatible with UTS REST API - version 0.51 Beta 4 | ## This file retrieves allows you to retrieve parents, children, ancestors, or descendants of a source-asserted concept, descriptor, or code. 5 | ## usage: perl retrieve-concept-info.pl -u your-umls-username -p your-umls-password -v version -i identifer -s source vocabulary 6 | ## If you do not provide the version parameter the script queries the latest avaialble UMLS publication. 7 | ## The full list of query parameters and fields available for source-asserted data retrieval is at: 8 | ## https://documentation.uts.nlm.nih.gov/rest/source-asserted-identifiers/index.html 9 | 10 | use lib "lib"; 11 | use strict; 12 | use warnings; 13 | use URI; 14 | use Authentication::TicketClient; 15 | use JSON; 16 | use REST::Client; 17 | use Data::Dumper; 18 | use Getopt::Std; 19 | our ($opt_u,$opt_p,$opt_v,$opt_s, $opt_i,$opt_o); 20 | getopt('upvsio'); 21 | my $username = $opt_u || die "please provide username"; 22 | my $password = $opt_p || die "please provide password"; 23 | my $version = defined $opt_v ? $opt_v : "current"; 24 | my $source = $opt_s || die "please provide a source vocabulary, such as SNOMEDCT_US"; 25 | my $id = $opt_i || die "please provide a source-asserted identifier"; 26 | my $operation = $opt_o || die "please specify 'children', 'ancestors', 'descendants', or 'parents'"; 27 | my $json; 28 | my $pageNum = 1; 29 | my $pageCount; 30 | my $resultCount = 0; 31 | 32 | ##create a ticket granting ticket for the session 33 | my $ticketClient = new TicketClient(username=>$opt_u,password=>$opt_p,service=>"http://umlsks.nlm.nih.gov",tgt=>"") || die "could not create TicketClient() object"; 34 | my $tgt = $ticketClient->getTgt(); 35 | my $uri = new URI("https://uts-ws.nlm.nih.gov"); 36 | my %parameters = (); 37 | my $client = REST::Client->new(); 38 | 39 | my $path = "/rest/content/".$version."/source/".$source."/".$id."/".$operation; 40 | 41 | 42 | do { 43 | 44 | $parameters{pageNumber} = $pageNum; 45 | $json = run_query($path,\%parameters); 46 | $pageCount = $json->{pageCount}; 47 | print qq{On page $pageNum of $pageCount pages\n}; 48 | 49 | foreach my $ui (@{ $json->{result} }) { 50 | 51 | printf "%s\n","ui- ".$ui->{ui}; 52 | printf "%s\n","Name- ".$ui->{name}; 53 | printf "%s\n","Atoms- ".$ui->{atoms}; 54 | printf "%s\n","Highest Ranking Atom- ".$ui->{defaultPreferredAtom}; 55 | printf "%s\n","Parents - ".$ui->{parents}; 56 | printf "%s\n","Children- ".$ui->{children}; 57 | printf "%s\n","Ancestors- ".$ui->{ancestors}; 58 | printf "%s\n","Descendants- ".$ui->{descendants}; 59 | printf "%s\n","Obsolete- ".$ui->{obsolete}; 60 | print qq{\n}; 61 | 62 | } 63 | 64 | print qq{-------\n}; 65 | $pageNum++; 66 | $resultCount += scalar(@{$json->{result}}); 67 | } 68 | 69 | while ($pageNum < ($pageCount + 1)); 70 | print qq{Found $resultCount total results\n}; 71 | 72 | 73 | sub format_json { 74 | my $json_in = shift; 75 | my $json = JSON->new; 76 | my $obj = $json->decode($json_in); 77 | #print Dumper(\$obj); 78 | return $obj; 79 | } 80 | 81 | sub run_query { 82 | 83 | my ($path, $parameters) = @_; 84 | $parameters{ticket} = $ticketClient->getServiceTicket(); 85 | $uri->path($path); 86 | $uri->query_form($parameters); 87 | print qq{$uri\n}; 88 | my $query = $client->GET($uri) || die "Could not execute query$!"; 89 | my $results = $query->responseCode() eq '200'? $query->responseContent: die "Could not execute query$!"; 90 | my $json = format_json($results); 91 | return $json; 92 | } 93 | -------------------------------------------------------------------------------- /samples/python/Authentication.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | ## 6/16/2017 - remove PyQuery dependency 3 | ## 5/19/2016 - update to allow for authentication based on api-key, rather than username/pw 4 | ## See https://documentation.uts.nlm.nih.gov/rest/authentication.html for full explanation 5 | 6 | import requests 7 | #from pyquery import PyQuery as pq 8 | import lxml.html as lh 9 | from lxml.html import fromstring 10 | 11 | uri="https://utslogin.nlm.nih.gov" 12 | #option 1 - username/pw authentication at /cas/v1/tickets 13 | #auth_endpoint = "/cas/v1/tickets/" 14 | #option 2 - api key authentication at /cas/v1/api-key 15 | auth_endpoint = "/cas/v1/api-key" 16 | 17 | class Authentication: 18 | 19 | #def __init__(self, username,password): 20 | def __init__(self, apikey): 21 | #self.username=username 22 | #self.password=password 23 | self.apikey=apikey 24 | self.service="http://umlsks.nlm.nih.gov" 25 | 26 | def gettgt(self): 27 | #params = {'username': self.username,'password': self.password} 28 | params = {'apikey': self.apikey} 29 | h = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", "User-Agent":"python" } 30 | r = requests.post(uri+auth_endpoint,data=params,headers=h) 31 | response = fromstring(r.text) 32 | ## extract the entire URL needed from the HTML form (action attribute) returned - looks similar to https://utslogin.nlm.nih.gov/cas/v1/tickets/TGT-36471-aYqNLN2rFIJPXKzxwdTNC5ZT7z3B3cTAKfSc5ndHQcUxeaDOLN-cas 33 | ## we make a POST call to this URL in the getst method 34 | tgt = response.xpath('//form/@action')[0] 35 | return tgt 36 | 37 | def getst(self,tgt): 38 | 39 | params = {'service': self.service} 40 | h = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", "User-Agent":"python" } 41 | r = requests.post(tgt,data=params,headers=h) 42 | st = r.text 43 | return st 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /samples/python/crosswalk.py: -------------------------------------------------------------------------------- 1 | ## Steven Emrick - steve.emrick@nih.gov 2 | ## usage: python crosswalk.py -k 3 | ## You can specify a specific UMLS version with the -v argument, but it is not required 4 | ## This reads a file with codes from the Human Phenotype Ontology and maps them to the US Edition of SNOMED CT through UMLS CUIs 5 | 6 | from __future__ import print_function 7 | from Authentication import * 8 | import requests 9 | import json 10 | import argparse 11 | import collections 12 | import sys 13 | import os 14 | 15 | if sys.version_info < (3, 0): 16 | reload(sys) 17 | sys.setdefaultencoding('utf-8') 18 | 19 | parser = argparse.ArgumentParser(description='process user given parameters') 20 | parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") 21 | parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") 22 | 23 | args = parser.parse_args() 24 | apikey = args.apikey 25 | version = args.version 26 | AuthClient = Authentication(apikey) 27 | 28 | ################################### 29 | #get TGT for our session 30 | ################################### 31 | 32 | tgt = AuthClient.gettgt() 33 | base_uri = "https://uts-ws.nlm.nih.gov" 34 | crosswalk_endpoint = "/rest/crosswalk/"+version+"/source/HPO" 35 | 36 | def crosswalk_code(path): 37 | query = {'ticket': AuthClient.getst(tgt),'targetSource': 'SNOMEDCT_US'} 38 | r = requests.get(base_uri + path, params=query) 39 | #print(r.url + "\n") 40 | items = json.loads(r.text) 41 | return items 42 | 43 | with open('hpo-codes.txt','r') as f: 44 | for line in f: 45 | ##get rid of newlines 46 | code = line.strip() 47 | path = crosswalk_endpoint+"/"+code 48 | try: 49 | results = crosswalk_code(path) 50 | for sourceAtomCluster in results["result"]: 51 | print('HPO Code - ' + code+ '\t' + 'SNOMEDCT concept -- ' + sourceAtomCluster["ui"] + ': ' + sourceAtomCluster["name"]) 52 | 53 | except ValueError: 54 | print("No result found for "+code) 55 | pass 56 | 57 | f.close() 58 | 59 | -------------------------------------------------------------------------------- /samples/python/get-content-view-members.py: -------------------------------------------------------------------------------- 1 | ## usage: python get-content-view-members.py -k -f 2 | ## You can specify a specific UMLS version with the -v argument, but it is not required 3 | ## This script will download the CORE Problem List subset of SNOMED CT 4 | ## and save to a file that you specify. There are around 250 pages of output to save - the CORE Problem list contains over 5,500 SNOMED CT codes 5 | ## and attributes. The script takes around 30 minutes to complete depending on your internet connection. 6 | 7 | from Authentication import * 8 | import requests 9 | import json 10 | import argparse 11 | import collections 12 | import sys 13 | reload(sys) 14 | sys.setdefaultencoding('utf-8') 15 | 16 | parser = argparse.ArgumentParser(description='process user given parameters') 17 | parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") 18 | parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") 19 | parser.add_argument("-f", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") 20 | 21 | args = parser.parse_args() 22 | apikey = args.apikey 23 | version = args.version 24 | outputfile=args.outputfile 25 | AuthClient = Authentication(apikey) 26 | 27 | ################################### 28 | #get TGT for our session 29 | ################################### 30 | 31 | tgt = AuthClient.gettgt() 32 | base_uri = "https://uts-ws.nlm.nih.gov" 33 | #C2711988 is the CUI for the SNOMED CT CORE Problem List content view 34 | #Full list of content views is here: https://www.nlm.nih.gov/research/umls/knowledge_sources/metathesaurus/release/content_views.html, 35 | #or over web services at https://uts-ws.nlm.nih.gov/rest/content-views/current?ticket=ST... 36 | content_view_endpoint = "/rest/content-views/"+version+"/CUI/C2711988/members" 37 | tgt = AuthClient.gettgt() 38 | pageNumber=1 39 | pageCount=1 40 | f = open(outputfile, 'w') 41 | 42 | #column headers - modify accordingly if you are computing a different subset 43 | f.write("SNOMED_CID|NAME|FIRST_IN_SUBSET|IS_RETIRED_FROM_SUBSET|OCCURRENCE|USAGE|REPLACED_BY_SNOMED_CID\n") 44 | 45 | ##There are ~ 250 pages in this subset, if you're using the default of 25 objects per page. 46 | while pageNumber<=pageCount: 47 | 48 | query = {'ticket':AuthClient.getst(tgt),'pageNumber':pageNumber} 49 | r = requests.get(base_uri+content_view_endpoint,params=query) 50 | print(r.url+"\n") 51 | r.encoding = 'utf-8' 52 | items = json.loads(r.text) 53 | pageCount=items["pageCount"] 54 | 55 | print("Fetching page " + str(pageNumber)+" of results\n") 56 | 57 | for result in items["result"]: 58 | 59 | f.write(result["ui"]+"|"+str(result["name"])) 60 | 61 | #MOST CONTENT VIEW MEMBERS DO NOT HAVE ATTRIBUTES, BUT FOR MEMBERS OF THE SNOMED CT CORE PROBLEM LIST 62 | #THESE ARE THE CURRENT LIST OF ATTRIBUTE NAMES THAT ARE DEFINED. HOWEVER, IN THE DATA THEY ARE NOT ALWAYS PRESENT 63 | #FOR EXAMPLE, IF IS_RETIRED_FROM_SUBSET = True, THERE IS NO 'OCCURRENCE' OR 'USAGE' ATTRIBUTE AVAILABLE, SO WE MUST CHECK AND THEN 64 | ##OUTPUT EMPTY FIELDS IF NEEDED 65 | attributes=result["contentViewMemberAttributes"] 66 | 67 | if len(attributes) > 0: 68 | 69 | cv_member_attributes = (("FIRST_IN_SUBSET",""), ('IS_RETIRED_FROM_SUBSET', ""), ("OCCURRENCE", ""), ("USAGE", ""), ("REPLACED_BY_SNOMED_CID", "")) 70 | cv_member_attributes = collections.OrderedDict(cv_member_attributes) 71 | 72 | existing_attributes = {} 73 | f.write("|") 74 | for attribute in attributes: 75 | existing_attributes[attribute["name"]] = attribute["value"] 76 | 77 | for cv_member_attribute in cv_member_attributes.keys(): 78 | 79 | #populate the attributes that are presented to us in the json 80 | if cv_member_attribute in existing_attributes.keys(): 81 | cv_member_attributes[cv_member_attribute] = existing_attributes[cv_member_attribute] 82 | 83 | for i,item in enumerate(list(cv_member_attributes.items())): 84 | 85 | ##either print a delimiter or a new line depending on where we are in the list of attributes 86 | if i < len(list(cv_member_attributes.items())) - 1: 87 | f.write(item[1]+"|") 88 | else: 89 | f.write(item[1]+"\n") 90 | 91 | else: 92 | f.write("\n") 93 | 94 | pageNumber+=1 -------------------------------------------------------------------------------- /samples/python/get-rxcui-ingredients.py: -------------------------------------------------------------------------------- 1 | #This script takes a list of rxnorm normal forms and attempts to associate with a MIN,PIN, or IN 2 | #coding=utf-8 3 | #get status of each rxcui 4 | #if active, get all ingredients (IN,MIN,PIN) 5 | #if there is a MIN, add that to the ingredients dictionary, ignore others 6 | #if there is a PIN, add that to the ingredients dictionary, ignore others 7 | #if only an IN exists add that to the ingredients dictionary 8 | ##at the end, for each IN, check and see if USP has a related salt form PIN via the UMLS API If so, remove the IN. 9 | 10 | import requests 11 | import json 12 | import argparse 13 | import simplejson 14 | import collections 15 | import sys 16 | import time 17 | from requests import utils 18 | from Authentication import * 19 | parser = argparse.ArgumentParser(description='process user given parameters') 20 | parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") 21 | parser.add_argument("-i", "--inputfile", required = True, dest = "inputfile", help = "enter a name for your input file") 22 | parser.add_argument("-o", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") 23 | 24 | 25 | uts = "https://uts-ws.nlm.nih.gov/" 26 | uri = "https://rxnav.nlm.nih.gov" 27 | #uri = "https://morc3.nlm.nih.gov" 28 | args = parser.parse_args() 29 | apikey = args.apikey 30 | inputfile=args.inputfile 31 | outputfile=args.outputfile 32 | 33 | ingredients = {} 34 | complete = False 35 | 36 | ################################### 37 | #get TGT for our session 38 | ################################### 39 | AuthClient = Authentication(apikey) 40 | tgt = AuthClient.gettgt() 41 | 42 | def get(path,query): 43 | try: 44 | time.sleep(.05) 45 | r = requests.get(uri+path, params=query, timeout=10) 46 | print(r.url) 47 | return simplejson.loads(r.text) 48 | except requests.exceptions.RequestException as e: 49 | print "Connection timing out..." 50 | sys.exit(1) 51 | 52 | 53 | def uts_get(path,query): 54 | r = requests.get(uts+path, params=query) 55 | print(r.url) 56 | if r.status_code == 404: 57 | #print "404" 58 | return "no usp atom" 59 | else: 60 | return simplejson.loads(r.text) 61 | 62 | def getRxCuiStatus(rxcui): 63 | path = "/REST/rxcui/"+rxcui+"/status.json" 64 | query = {} 65 | results = get(path,query) 66 | return results 67 | 68 | def checkIngredient(rxcui): 69 | path = "/REST/rxcui/"+rxcui+"/related.json?tty=IN+MIN+PIN" 70 | query = {} 71 | results=get(path,query) 72 | return results 73 | 74 | def getSaltFormCuis(rxcui): 75 | cuis = {} 76 | path = "/REST/rxcui/"+rxcui+"/related.json?tty=PIN" 77 | query = {} 78 | results=get(path,query) 79 | for group in results["relatedGroup"]["conceptGroup"]: 80 | try: 81 | for properties in group["conceptProperties"]: 82 | #print properties["rxcui"]+", "+ properties["name"] 83 | cuis[properties["rxcui"]] = {"rxcui":properties["rxcui"],"tty":properties["tty"],"name":properties["name"],"umlscui":properties["umlscui"]} 84 | 85 | except: 86 | KeyError 87 | #print cuis 88 | return cuis 89 | 90 | 91 | def checkForUspAtom(cui): 92 | path = "/rest/content/current/CUI/"+cui+"/atoms" 93 | query = {"sabs":"USPMG","ttys":"PT","ticket":AuthClient.getst(tgt)} 94 | results = uts_get(path,query) 95 | return results 96 | 97 | def parseIngredient(related): 98 | 99 | results = {} 100 | global complete 101 | complete = False 102 | 103 | for group in related["relatedGroup"]["conceptGroup"]: 104 | try: 105 | for properties in group["conceptProperties"]: 106 | #print properties["rxcui"]+", "+ properties["name"] 107 | results[group["tty"]] = {"rxcui":properties["rxcui"],"tty":properties["tty"],"name":properties["name"]} 108 | 109 | except: 110 | KeyError 111 | 112 | 113 | for tty in sorted(results.keys()): 114 | #print tty 115 | if "MIN" in results and complete == False: 116 | #print results["MIN"] 117 | if results["MIN"]["rxcui"] not in ingredients.keys(): 118 | ingredients[results["MIN"]["rxcui"]] = results["MIN"] 119 | complete = True 120 | 121 | elif "MIN" not in results and "PIN" in results and complete == False: 122 | #print results["PIN"] 123 | if results["PIN"]["rxcui"] not in ingredients.keys(): 124 | ingredients[results["PIN"]["rxcui"]] = results["PIN"] 125 | #print results["PIN"]["name"] 126 | complete = True 127 | 128 | 129 | elif "MIN" not in results and "PIN" not in results and results["IN"]["rxcui"] not in ingredients.keys() and complete == False: 130 | if results["IN"]["rxcui"] not in ingredients.keys(): 131 | ingredients[results["IN"]["rxcui"]] = results["IN"] 132 | complete = True 133 | 134 | 135 | with open(inputfile, 'r') as f: 136 | for line in f: 137 | rxcui = line.strip() 138 | json = getRxCuiStatus(rxcui) 139 | status = json["rxcuiStatus"]["status"].encode('utf-8') 140 | 141 | if status == "Active": 142 | related = checkIngredient(rxcui) 143 | parseIngredient(related) 144 | elif status == "Remapped" or status == "Quantified": 145 | for remapped in json["rxcuiStatus"]["minConceptGroup"]["minConcept"]: 146 | related = checkIngredient(remapped["rxcui"]) 147 | parseIngredient(related) 148 | 149 | 150 | f.close() 151 | 152 | w = open(outputfile, 'w') 153 | 154 | ##cleanup - remove INs that have a salt form with an exising USP atom, and add the USP salt form if it is not already in the ingredients dictionary 155 | for rxcui in ingredients.keys(): 156 | if ingredients[rxcui]["tty"] == "IN": 157 | saltFormCuis = getSaltFormCuis(rxcui) 158 | for pin in saltFormCuis.keys(): 159 | ##not all PINs in RxNorm will have UMLS CUIs 160 | #print saltFormCuis[pin] 161 | if saltFormCuis[pin]["umlscui"]: 162 | uspAtom = checkForUspAtom(saltFormCuis[pin]["umlscui"]) 163 | if uspAtom != "no usp atom" and rxcui in ingredients.iterkeys(): 164 | print "removing " + ingredients[rxcui]["name"] 165 | #remove the single ingredient form 166 | del ingredients[rxcui] 167 | #add the USP salt form 168 | if saltFormCuis[pin]["rxcui"] not in ingredients.iterkeys(): 169 | print "adding " + saltFormCuis[pin]["name"] 170 | #get rid of the UMLS CUI - we don't need it anymore 171 | del saltFormCuis[pin]["umlscui"] 172 | ingredients[rxcui] = saltFormCuis[pin] 173 | ##output results 174 | for rows in sorted(ingredients.values()): 175 | line = '|'.join(rows.values()) 176 | w.write(line+"\n") 177 | 178 | -------------------------------------------------------------------------------- /samples/python/get-rxcui-status.py: -------------------------------------------------------------------------------- 1 | #This script provides a way to query the RxNorm API to determine the status of an RxCUI 2 | #coding=utf-8 3 | import requests 4 | import json 5 | import argparse 6 | import xml.etree.ElementTree as ET 7 | import simplejson 8 | import time 9 | import sys 10 | from urllib import unquote 11 | from requests import utils 12 | parser = argparse.ArgumentParser(description='process user given parameters') 13 | parser.add_argument("-i", "--inputfile", required = True, dest = "inputfile", help = "enter a name for your input file") 14 | parser.add_argument("-o", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") 15 | 16 | 17 | uri = "https://morc3.nlm.nih.gov" 18 | args = parser.parse_args() 19 | inputfile=args.inputfile 20 | outputfile=args.outputfile 21 | 22 | 23 | def get(path,query): 24 | time.sleep(.05) 25 | r = requests.get(uri+path, params=query) 26 | print(r.url) 27 | return simplejson.loads(r.text) 28 | 29 | def getRxCuiStatus(rxcui): 30 | path = "/RxNormRest/rxcui/"+rxcui+"/status.json" 31 | query = {} 32 | results = get(path,query) 33 | return results 34 | 35 | 36 | w = open(outputfile, 'w') 37 | 38 | rxcuis = {} 39 | 40 | with open(inputfile, 'r') as f: 41 | for line in f: 42 | rxcui = line.strip() 43 | json = getRxCuiStatus(rxcui) 44 | status = json["rxcuiStatus"]["status"].encode('utf-8') 45 | 46 | if not status == "Active": 47 | if status == "Remapped" or status == "Quantified": 48 | #print rxcui +"\t" + status 49 | for remapped in json["rxcuiStatus"]["minConceptGroup"]["minConcept"]: 50 | print rxcui +"\t"+ status+"\t"+ remapped["rxcui"] 51 | rxcuis[rxcui] = {"rxcui":rxcui,"status":status,"remapped":remapped["rxcui"]} 52 | 53 | else: 54 | rxcuis[rxcui] = {"rxcui":rxcui,"status":status,"remapped":" "} 55 | 56 | #output 57 | for rows in sorted(rxcuis.values()): 58 | line = '|'.join(rows.values()) 59 | w.write(line+"\n") 60 | -------------------------------------------------------------------------------- /samples/python/get-rxcuis-by-tty.py: -------------------------------------------------------------------------------- 1 | #This script provides a way to query the RxNorm API for 2 | #prescribable drugs based on term types 3 | 4 | import requests 5 | import json 6 | import argparse 7 | import xml.etree.ElementTree as ET 8 | import sys 9 | from urllib import unquote 10 | from requests import utils 11 | 12 | parser = argparse.ArgumentParser(description='process user given parameters') 13 | parser.add_argument("-ttys", "--termtypes", required = True, dest = "ttys", help = "Enter TTYs to query, separated by a space") 14 | parser.add_argument("-o", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") 15 | 16 | 17 | uri = "https://rxnav.nlm.nih.gov" 18 | args = parser.parse_args() 19 | ttys = args.ttys 20 | outputfile=args.outputfile 21 | o = open(outputfile, 'w') 22 | 23 | 24 | def get(path,query): 25 | 26 | r = requests.get(uri+path, params=query) 27 | #print(r.url) 28 | return r.text.encode('utf-8') 29 | 30 | def getRxCuisByTermType(): 31 | path = "/REST/allconcepts" 32 | query = {'tty':ttys} 33 | results = get(path,query) 34 | return results 35 | 36 | 37 | def filterRxCuis(rxcui,filter): 38 | path = "/REST/rxcui/"+rxcui+"/filter" 39 | query = {'propName': filter} 40 | results = get(path,query) 41 | return results 42 | 43 | results = getRxCuisByTermType() 44 | xml = ET.fromstring(results) 45 | 46 | for rxcuis in xml.findall(".//minConcept"): 47 | rxcui = rxcuis.find("rxcui").text 48 | 49 | #now make sure the concept is part of the prescribable subset 50 | filtered = filterRxCuis(rxcui,'prescribable') 51 | rxnormdata = ET.fromstring(filtered) 52 | 53 | #only output if the concept belongs to the prescribable subset of RxNorm 54 | if len(rxnormdata) > 0: 55 | print rxnormdata.find('rxcui').text + " is prescribable" 56 | o.write(rxnormdata.find('rxcui').text+"\n") 57 | 58 | -------------------------------------------------------------------------------- /samples/python/hpo-codes.txt: -------------------------------------------------------------------------------- 1 | HP:0001735 2 | HP:0001947 3 | HP:0100631 4 | HP:0001022 5 | HP:0001596 6 | HP:0000646 7 | HP:0009916 8 | HP:0100845 9 | HP:0001102 10 | HP:0000739 11 | HP:0000787 12 | HP:0011484 13 | HP:0001871 14 | HP:0030346 15 | -------------------------------------------------------------------------------- /samples/python/retrieve-cui-or-code.py: -------------------------------------------------------------------------------- 1 | ################################################################################################# 2 | # usage of the script 3 | # usage: python retrieve-cui-or-code.py -k APIKEY -v VERSION -i IDENTIFIER -s SOURCE 4 | # If you do not provide the -s parameter, the script assumes you are retrieving information for a 5 | # known UMLS CUI 6 | ################################################################################################# 7 | 8 | from Authentication import * 9 | import requests 10 | import json 11 | import argparse 12 | 13 | parser = argparse.ArgumentParser(description='process user given parameters') 14 | #parser.add_argument("-u", "--username", required = True, dest="username", help = "enter username") 15 | #parser.add_argument("-p", "--password", required = True, dest="password", help = "enter passowrd") 16 | parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") 17 | parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") 18 | parser.add_argument("-i", "--identifier", required = True, dest="identifier", help = "enter identifier example-C0018787") 19 | parser.add_argument("-s", "--source", required = False, dest="source", help = "enter source name if known") 20 | 21 | args = parser.parse_args() 22 | 23 | #username = args.username 24 | #password = args.password 25 | apikey = args.apikey 26 | version = args.version 27 | identifier = args.identifier 28 | source = args.source 29 | AuthClient = Authentication(apikey) 30 | 31 | ################################### 32 | #get TGT for our session 33 | ################################### 34 | 35 | tgt = AuthClient.gettgt() 36 | uri = "https://uts-ws.nlm.nih.gov" 37 | 38 | try: 39 | source 40 | except NameError: 41 | source = None 42 | 43 | ##if we don't specify a source vocabulary, assume we're retrieving UMLS CUIs 44 | if source is None: 45 | content_endpoint = "/rest/content/"+str(version)+"/CUI/"+str(identifier) 46 | 47 | else: 48 | content_endpoint = "/rest/content/"+str(version)+"/source/"+str(source)+"/"+str(identifier) 49 | 50 | ##ticket is the only parameter needed for this call - paging does not come into play because we're only asking for one Json object 51 | query = {'ticket':AuthClient.getst(tgt)} 52 | r = requests.get(uri+content_endpoint,params=query) 53 | r.encoding = 'utf-8' 54 | items = json.loads(r.text) 55 | jsonData = items["result"] 56 | 57 | ##uncomment the print statment if you want the raw json output, or you can just look at the documentation :=) 58 | #https://documentation.uts.nlm.nih.gov/rest/concept/index.html#sample-output 59 | #https://documentation.uts.nlm.nih.gov/rest/source-asserted-identifiers/index.html#sample-output 60 | #print (json.dumps(items, indent = 4)) 61 | 62 | ############################ 63 | ### Print out fields #### 64 | 65 | classType = jsonData["classType"] 66 | name = jsonData["name"] 67 | ui = jsonData["ui"] 68 | AtomCount = jsonData["atomCount"] 69 | Definitions = jsonData["definitions"] 70 | Atoms = jsonData["atoms"] 71 | DefaultPreferredAtom = jsonData["defaultPreferredAtom"] 72 | 73 | ## print out the shared data elements that are common to both the 'Concept' and 'SourceAtomCluster' class 74 | print ("classType: " + classType) 75 | print ("ui: " + ui) 76 | print ("Name: " + name) 77 | print ("AtomCount: " + str(AtomCount)) 78 | print ("Atoms: " + Atoms) 79 | print ("Default Preferred Atom: " + DefaultPreferredAtom) 80 | 81 | ## These data elements may or may not exist depending on what class ('Concept' or 'SourceAtomCluster') you're dealing with so we check for each one. 82 | try: 83 | jsonData["definitions"] 84 | print ("definitions: " + jsonData["definitions"]) 85 | except: 86 | pass 87 | 88 | try: 89 | jsonData["parents"] 90 | print ("parents: " + jsonData["parents"]) 91 | except: 92 | pass 93 | 94 | try: 95 | jsonData["children"] 96 | print ("children: " + jsonData["children"]) 97 | except: 98 | pass 99 | 100 | try: 101 | jsonData["relations"] 102 | print ("relations: " + jsonData["relations"]) 103 | except: 104 | pass 105 | 106 | try: 107 | jsonData["descendants"] 108 | print ("descendants: " + jsonData["descendants"]) 109 | except: 110 | pass 111 | 112 | try: 113 | jsonData["semanticTypes"] 114 | print("Semantic Types:") 115 | for stys in jsonData["semanticTypes"]: 116 | print("uri: "+ stys["uri"]) 117 | print("name: "+ stys["name"]) 118 | 119 | except: 120 | pass 121 | -------------------------------------------------------------------------------- /samples/python/retrieve-usp-atoms-from-umls.py: -------------------------------------------------------------------------------- 1 | ###Takes a list of CUIs that result from /search?string=PT,IN,MIN,PIN&inputType=tty&sabs=RXNORM,USPMG. 2 | ###For each of theses CUIs, output the atoms 3 | ###If there is a PIN from RxNorm in the same CUI as a USPMG atom, find the RxNorm associated single ingredient form and 4 | ###remove it from the final list 5 | ###Then go through again and remove USP atoms that are in the same CUI as an RxNorm atom 6 | 7 | from Authentication import * 8 | import requests 9 | import simplejson 10 | import argparse 11 | import collections 12 | import sys 13 | from collections import OrderedDict 14 | reload(sys) 15 | sys.setdefaultencoding('utf-8') 16 | 17 | parser = argparse.ArgumentParser(description='process user given parameters') 18 | parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") 19 | parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") 20 | parser.add_argument("-o", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") 21 | parser.add_argument("-s", "--sabs", required = False, dest="sabs",help = "enter a comma-separated list of vocabularies, like MSH, SNOMEDCT_US, or RXNORM") 22 | parser.add_argument("-t", "--ttys", required = False, dest="ttys",help = "enter a comma-separated list of term types, like PT,SY,IN") 23 | parser.add_argument("-i", "--inputfile", required = True, dest = "inputfile", help = "enter a name for your input file") 24 | 25 | 26 | args = parser.parse_args() 27 | apikey = args.apikey 28 | version = args.version 29 | outputfile = args.outputfile 30 | inputfile = args.inputfile 31 | sabs = args.sabs 32 | ttys = args.ttys 33 | AuthClient = Authentication(apikey) 34 | 35 | ################################### 36 | #get TGT for our session 37 | ################################### 38 | 39 | tgt = AuthClient.gettgt() 40 | base_uri = "https://uts-ws.nlm.nih.gov" 41 | rxnorm = "https://rxnav.nlm.nih.gov" 42 | pageNumber=1 43 | pageCount=1 44 | auis = {} 45 | if outputfile: 46 | o = open(outputfile, 'w') 47 | 48 | 49 | def rxnorm_get(path,query): 50 | r = requests.get(rxnorm+path, params=query) 51 | print(r.url) 52 | return simplejson.loads(r.text) 53 | 54 | def uts_get(path,query): 55 | r = requests.get(base_uri+path, params=query) 56 | print(r.url) 57 | return simplejson.loads(r.text) 58 | 59 | def getSingleIngredientForm(rxcui): 60 | path = "/REST/rxcui/"+rxcui+"/related.json?tty=IN" 61 | query = {} 62 | #print(r.url) 63 | results=rxnorm_get(path,query) 64 | return results 65 | 66 | def retrieveConceptAtoms(cui): 67 | 68 | path = "/rest/content/"+version+"/CUI/"+cui+"/atoms" 69 | query = {"ticket":AuthClient.getst(tgt)} 70 | if sabs: 71 | query["sabs"] = sabs 72 | if ttys: 73 | query["ttys"] = ttys 74 | 75 | 76 | results = uts_get(path,query) 77 | return results 78 | 79 | with open(inputfile, 'r') as f: 80 | 81 | for line in f: 82 | 83 | cui = line.strip() 84 | json = retrieveConceptAtoms(cui) 85 | for atoms in json["result"]: 86 | 87 | slash = atoms["code"].rfind("/") 88 | code = atoms["code"][slash+1:] 89 | #rootSources[atoms["rootSource"]] = code+"\t"+atoms["termType"]+"\t"+atoms["name"] 90 | auis[atoms["ui"]] = {"cui":cui,"code":code,"tty":atoms["termType"],"name":atoms["name"],"sab":atoms["rootSource"]} 91 | 92 | 93 | f.close() 94 | ##Cleanup - find all PIN atoms in CUI with a USP atom 95 | ##Find related single ingredient form and remove it. 96 | 97 | singleIngredientCuis = [] 98 | 99 | ##identify PINS in the list of all atoms. 100 | ##If there is a PIN from RxNorm that shares a CUI with a USPMG atom, find the CUI of the IN form (/rxcui/related?tty=IN) and remove all 101 | ##atoms containing that CUI 102 | 103 | for aui1 in auis.keys(): 104 | print '|'.join(auis[aui1].values()) 105 | if auis[aui1]["tty"] == "PIN": 106 | print "Found salt form of " + auis[aui1]["cui"] + " " + auis[aui1]["name"] 107 | print "searching for " + auis[aui1]["code"] + " from " + auis[aui1]["sab"] 108 | for aui2 in auis.keys(): 109 | if auis[aui1]["cui"] == auis[aui2]["cui"] and auis[aui2]["sab"] == "USPMG": 110 | singleIngredients = getSingleIngredientForm(auis[aui1]["code"]) 111 | for properties in singleIngredients["relatedGroup"]["conceptGroup"][0]["conceptProperties"]: 112 | singleIngredientCuis.append(properties["umlscui"]) 113 | 114 | ## find the intersection of the 2 dictionaries, and delete the auis that represent single ingredients that already rels to USP salt form 115 | 116 | sameCuis = [auis[cui]["cui"] for cui in auis.keys() if auis[cui]["cui"] in singleIngredientCuis] 117 | 118 | print "Found " + str(len(auis)) + " total atoms in the result set\n" 119 | print "Found " +str(len(sameCuis)) + " CUIs with single ingredient atoms\n" 120 | 121 | for cui in auis.keys(): 122 | if auis[cui]["cui"] in sameCuis: 123 | print "removing " + auis[cui]["name"] 124 | del auis[cui] 125 | 126 | 127 | 128 | removals = [] 129 | log = open("removal-log.txt",'w') 130 | 131 | for cui1 in auis.keys(): 132 | for cui2 in auis.keys(): 133 | if auis[cui2]["sab"] == "RXNORM" and auis[cui1]["sab"] == "USPMG" and (auis[cui1]["cui"] == auis[cui2]["cui"]): 134 | print "Found " + cui1 + " and " + cui2 +" in " + auis[cui1]["cui"] 135 | #identify all USPMG atoms that are merged into the same UMLS CUI as an RxNorm atom 136 | removals.append(cui1) 137 | 138 | print "Removing " + str(len(removals)) + " USP atoms that share a CUI with RxNorm\n" 139 | 140 | for cui in auis.keys(): 141 | if cui in removals: 142 | line = '|'.join(auis[cui].values()) 143 | log.write(line+"\n") 144 | del auis[cui] 145 | 146 | print "Total of "+ str(len(auis)) + " atoms are left in results" 147 | 148 | w = open(outputfile, 'w') 149 | 150 | for fields in auis.values(): 151 | line = '|'.join(fields.values()) 152 | print line+"\n" 153 | w.write(line+"\n") 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | -------------------------------------------------------------------------------- /samples/python/retrieve-value-set-info.py: -------------------------------------------------------------------------------- 1 | ###A script to retrieve code system information from the value set bps definition document. 2 | ###Note that the rows of the input file are expected to have the 3 | 4 | from Authentication import * 5 | import requests 6 | import json 7 | import argparse 8 | import xml.etree.ElementTree as ET 9 | import sys 10 | 11 | parser = argparse.ArgumentParser(description='process user given parameters') 12 | parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") 13 | parser.add_argument("-p", "--profile", required = False, dest = "profile", help = "Enter a binding profile, such as MU2 2016 Update") 14 | parser.add_argument("-o", "--outputfile", required = True, dest = "outputfile", help = "enter a name for your output file") 15 | parser.add_argument("-i", "--inputfile", required = True, dest = "inputfile", help = "enter a name for your input file") 16 | 17 | 18 | args = parser.parse_args() 19 | apikey = args.apikey 20 | profile = args.profile 21 | outputfile=args.outputfile 22 | inputfile=args.inputfile 23 | 24 | AuthClient = Authentication(apikey) 25 | tgt = AuthClient.gettgt() 26 | 27 | uri = "https://vsac.nlm.nih.gov/vsac/svs/RetrieveMultipleValueSets" 28 | 29 | o = open(outputfile, 'w') 30 | 31 | def getCodeSystem(id): 32 | ticket = AuthClient.getst(tgt) 33 | query = {'id':id,'ticket':ticket,'version':profile} 34 | r = requests.get(uri, params=query) 35 | print(r.url) 36 | return r.text.encode('utf-8') 37 | 38 | 39 | with open(inputfile,'r') as f: 40 | 41 | for line in f: 42 | oid,name,memberOid,memberOidName = line.strip().split("|") 43 | if len(memberOid) == 0: 44 | codeSystem = getCodeSystem(oid) 45 | else: 46 | codeSystem = getCodeSystem(memberOid) 47 | 48 | xml = ET.fromstring(codeSystem) 49 | ns = {"ns0":"urn:ihe:iti:svs:2008"} 50 | codeSystemInfo = {} 51 | for concepts in xml.findall(".//ns0:ConceptList/ns0:Concept",ns): 52 | cs = concepts.get('codeSystemName') 53 | codeSystemVersion = concepts.get('codeSystemVersion') 54 | codeSystemInfo.setdefault(cs,[]).append(codeSystemVersion) 55 | sys.stdout.write(oid+"|"+memberOid) 56 | 57 | for k,v in codeSystemInfo.items(): 58 | sys.stdout.write(k+"|"+','.join(set(v))) 59 | #o.write(oid+"|"+name+"|"+memberOid+"|"+k+"|"+','.join(set(v))) 60 | o.write(oid + "|" + name + "|" + memberOid + "|"+ memberOidName +"|" + k +"|"+','.join(set(v))+"\n") 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /samples/python/search-terms.py: -------------------------------------------------------------------------------- 1 | ################################################################################# 2 | # usage of the script 3 | # usage: python search-terms.py -k APIKEY -v VERSION -s STRING 4 | # see https://documentation.uts.nlm.nih.gov/rest/search/index.html for full docs 5 | # on the /search endpoint 6 | ################################################################################# 7 | 8 | from __future__ import print_function 9 | from Authentication import * 10 | import requests 11 | import json 12 | import argparse 13 | 14 | parser = argparse.ArgumentParser(description='process user given parameters') 15 | #parser.add_argument("-u", "--username", required = True, dest="username", help = "enter username") 16 | #parser.add_argument("-p", "--password", required = True, dest="password", help = "enter passowrd") 17 | parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") 18 | parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") 19 | parser.add_argument("-s", "--string", required = True, dest="string", help = "enter a search term, like 'diabetic foot'") 20 | 21 | args = parser.parse_args() 22 | #username = args.username 23 | #password = args.password 24 | apikey = args.apikey 25 | version = args.version 26 | string = args.string 27 | uri = "https://uts-ws.nlm.nih.gov" 28 | content_endpoint = "/rest/search/"+version 29 | ##get at ticket granting ticket for the session 30 | AuthClient = Authentication(apikey) 31 | tgt = AuthClient.gettgt() 32 | pageNumber=0 33 | 34 | while True: 35 | ##generate a new service ticket for each page if needed 36 | ticket = AuthClient.getst(tgt) 37 | pageNumber += 1 38 | query = {'string':string,'ticket':ticket, 'pageNumber':pageNumber} 39 | #query['includeObsolete'] = 'true' 40 | #query['includeSuppressible'] = 'true' 41 | #query['returnIdType'] = "sourceConcept" 42 | #query['sabs'] = "SNOMEDCT_US" 43 | r = requests.get(uri+content_endpoint,params=query) 44 | r.encoding = 'utf-8' 45 | items = json.loads(r.text) 46 | jsonData = items["result"] 47 | #print (json.dumps(items, indent = 4)) 48 | 49 | print("Results for page " + str(pageNumber)+"\n") 50 | 51 | for result in jsonData["results"]: 52 | 53 | try: 54 | print("ui: " + result["ui"]) 55 | except: 56 | NameError 57 | try: 58 | print("uri: " + result["uri"]) 59 | except: 60 | NameError 61 | try: 62 | print("name: " + result["name"]) 63 | except: 64 | NameError 65 | try: 66 | print("Source Vocabulary: " + result["rootSource"]) 67 | except: 68 | NameError 69 | 70 | print("\n") 71 | 72 | 73 | ##Either our search returned nothing, or we're at the end 74 | if jsonData["results"][0]["ui"] == "NONE": 75 | break 76 | print("*********") 77 | 78 | 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /samples/python/walk-hierarchy.py: -------------------------------------------------------------------------------- 1 | ################################################################################################################################################################## 2 | # usage of the script 3 | # usage: python walk-hierarchy.py -k APIKEY -v VERSION -s SOURCE -i IDENTIFIER -o operation 4 | # note that computing descendants can take time, especially for terminology concepts with many descendants, closer to the tree-top of a given source vocabulary. 5 | ################################################################################################################################################################## 6 | 7 | from __future__ import print_function 8 | from Authentication import * 9 | import requests 10 | import json 11 | import argparse 12 | 13 | parser = argparse.ArgumentParser(description='process user given parameters') 14 | #parser.add_argument("-u", "--username", required = True, dest="username", help = "enter username") 15 | #parser.add_argument("-p", "--password", required = True, dest="password", help = "enter passowrd") 16 | parser.add_argument("-k", "--apikey", required = True, dest = "apikey", help = "enter api key from your UTS Profile") 17 | parser.add_argument("-v", "--version", required = False, dest="version", default = "current", help = "enter version example-2015AA") 18 | parser.add_argument("-s", "--source", required = True, dest="source", help = "enter a source vocabulary, like 'SNOMEDCT_US'") 19 | parser.add_argument("-i", "--identifier", required = True, dest="identifier", help = "enter an identifier, like 9468002") 20 | parser.add_argument("-o", "--operation", required = True, dest="operation", help = "choose an operation such as 'children', 'parents', 'descendants', or 'ancestors'") 21 | 22 | 23 | args = parser.parse_args() 24 | #username = args.username 25 | #password = args.password 26 | apikey = args.apikey 27 | version = args.version 28 | source = args.source 29 | identifier = args.identifier 30 | operation = args.operation 31 | uri = "https://uts-ws.nlm.nih.gov" 32 | content_endpoint = "/rest/content/"+version+"/source/"+source+"/"+identifier+"/"+operation 33 | 34 | ##get at ticket granting ticket for the session 35 | AuthClient = Authentication(apikey) 36 | tgt = AuthClient.gettgt() 37 | pageNumber=1 38 | 39 | while True: 40 | 41 | query = {'ticket':AuthClient.getst(tgt),'pageNumber':pageNumber} 42 | r = requests.get(uri+content_endpoint,params=query) 43 | print(r.url) 44 | r.encoding = 'utf-8' 45 | items = json.loads(r.text) 46 | pageCount=items["pageCount"] 47 | 48 | 49 | print("Results for page " + str(pageNumber)+"\n") 50 | for result in items["result"]: 51 | 52 | try: 53 | print("ui: " + result["ui"]) 54 | except: 55 | NameError 56 | try: 57 | print("uri: " + result["uri"]) 58 | except: 59 | NameError 60 | try: 61 | print("name: " + result["name"]) 62 | except: 63 | NameError 64 | try: 65 | print("Source Vocabulary: " + result["rootSource"]) 66 | except: 67 | NameError 68 | print("\n") 69 | pageNumber += 1 70 | 71 | if pageNumber > pageCount: 72 | print("End of result set") 73 | break 74 | 75 | print("*********") 76 | --------------------------------------------------------------------------------